EDIT: I agree with Morg. If coding right also results in faster code there is no reason not to do that.
Some approaches are NOT acceptable, it's not about optimizing prematurely, it's about coding obvious crap.
While you may be used to the usual "code crap, fix later" and "waste cycles, there are too many of it" , it doesn't mean you're right.
Everyone says it but you're still running on C (linux, unix), you're still going nuts over scaling issues (lol nosql for everyone) and you're still paying your amazon cloud bill.
I have several sites running on a single smallest Linode, and the CPU utilization virtually never cracks 1%.
Also, note that I am not advocating "coding crap". I'm talking about not berating coworkers over the nanosecond cost of an extra modulo inside a loop.
The others I will be pleased not to work with.
And the anti-optimization argument would be correct if: -typing represented more than 1% of dev work -code was never reused -code was never massively used -code had a short lifespan
So let me help you see clearly: -I'm not a typist -Every bad code tutorial out there creates millions of code bits that contain the N times slower version, with an aggregate impact that actually matters -Any 10% opt mistake in a codebase like iptables would cause more carbon than you can imagine -Fortran is still in use because it's the fastest language there is with the best math libraries.
Those seem to be eternal so far, and C seems to remain the only other relevant language throughout the short history of coding.
Sure, there are much more problematic cases than the dumb even odd example, but I picked that one because many would recognize it.
If your code is expressive, easy to reason about and fast enough, then less expressive, harder to reason about and even faster code isn't more correct.
Who knows maybe the trend will be 3 colors instead of two. Or maybe it'll be another instruction that's wrongly abused. Or another compiler that actually sucks, like most JS interpreters.
The idea really is to use the simplest logical approach to the problem rather than the wrong one.
In the very well known case of the alt row table, it looks to me like we're alternating odd and even, why not just code that to start with, before any optimization ?
for(t = 0; t < T; t++)
for(i = 0; i < NN; i++)
A[i%N] = 0;
which is optimised to this, without a modulo in sight: _invt = (NN-1)/N;
for(t = 0; t <= T-1; t++) {
for(_Mdi = 0; _Mdi <= _invt; _Mdi++) {
_peeli = 0;
for(i = N*_Mdi; i <= min(N*_Mdi+N-1,NN-1); i++) {
A[_peeli] = 0;
_peeli = _peeli + 1;
}
}
}
I find the modulo easier to read in this case, but I guess that's a question of taste. It's certainly not 'wrong' to use a modulo, and probably worth the trade off in most cases if it makes your code clearer.