3 ms·
1 isn't really the same thing. I don't know any compiler that would turn for (i = 0; i < length; i++) into for (i = length; i != 0; i--) Which is
by taeric 4y ago
1 isn't really the same thing. I don't know any compiler that would turn
for (i = 0; i < length; i++)
into
for (i = length; i != 0; i--)
Which is what I read 1 to be.
As for why you sometimes do one over the other. I think it is true that computers branch on zero more easily than other values. That said, I'd be a little surprised to know it makes a difference that can be measured in any meaningful program.
- whoopdedo 4y agoClang will if `i` is not referenced anywhere else. e.g. int i,n; for (i = 0; i < length; i++) n = something(); return n; It's also free to treat `i` as a different variable: int i,n = 0; for (i = 0; i < length; i++) something(n++); /* Compiler will merge the n and i variables */ return n; Or eliminate the loop completely if there are no side effects. int i, n = 0; for (i = 0; i < length; i++) n = i + 1; /* A very roundabout way to say "n = length" */ return n;
- taeric 4y agoIn neither of those did the sequence change direction, though?
- thrwawy74 4y agoSee this is why I felt I was obsessing over something very small. Loop inversion, unrolling, and splitting. The compiler can do so much with a loop to make it run faster on 'this machine' to optimize for speed, memory use, or binary size.
- whoopdedo 4y agoSorry, I didn't copy the assembler output for brevity but Clang generates `decl %esi` (or `addl $-1,%ebx` depending on the version) in the first case.
- taeric 4y agoDo you know of any cases where it changes the sequence of seen values? I'm assuming it can in this case, because the i is never used?