I doubt the answer to this question has much to do with performance. I wrote a version of each for loop in c++ and used GCC to get the resulting ASM. The "Enhanced For Loop" (version 2) actually has one more instruction subl $1, -8(%rbp)
overall than the "Non Enhanced For Loop".
Either way the performance difference is negligible. This sort of code choice should be made based upon readability of the code and wether or not you want the operation inside the for loop applied on the elements in the forward direction or the reverse direction. IE searching from beginning of a list or the end of a list.
First version of the for loop:
int main(int argc, char* argv[])
{
int lengthOfSomething = 10;
int valueToInc = 0;
for(int i = 0; i < lengthOfSomething; i++)
{
valueToInc += i;
}
}
Resulting ASM
.file "main.cpp"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl %edi, -20(%rbp)
movq %rsi, -32(%rbp)
movl $10, -12(%rbp)
movl $0, -4(%rbp)
movl $0, -8(%rbp)
jmp .L2
.L3:
movl -8(%rbp), %eax
addl %eax, -4(%rbp)
addl $1, -8(%rbp)
.L2:
movl -8(%rbp), %eax
cmpl -12(%rbp), %eax
jl .L3
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.2 20140206 (prerelease)"
.section .note.GNU-stack,"",@progbits
Second version of the for loop:
int main(int argc, char* argv[])
{
int lengthOfSomething = 10;
int valueToInc = 0;
for(int i = lengthOfSomething - 1; i >= 0; i--)
{
valueToInc += i;
}
}
Resulting ASM
.file "main2.cpp"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl %edi, -20(%rbp)
movq %rsi, -32(%rbp)
movl $10, -12(%rbp)
movl $0, -4(%rbp)
movl -12(%rbp), %eax
subl $1, %eax
movl %eax, -8(%rbp)
jmp .L2
.L3:
movl -8(%rbp), %eax
addl %eax, -4(%rbp)
subl $1, -8(%rbp)
.L2:
cmpl $0, -8(%rbp)
jns .L3
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.2 20140206 (prerelease)"
.section .note.GNU-stack,"",@progbits