What is the difference?

65 Views Asked by At

I was wondering,is there a difference in execution time between ++i and i++ in the for loop increment?

1)for(int i=0;i<100;++i)

2)for(int i=0;i<100;i++)

I have heard that the one with the pre-increment uses less registers, and hence, it is faster.

Is it correct?

2

There are 2 best solutions below

0
On

Not these days no; if you can optimise it in your head then you can bet your bottom dollar that a compiler can also optimise it.

If you are in any doubt, check the generated assembly / bytecode &c.

6
On

This seems to be C code. In this case, there isn't any difference: try compiling those two sources with a compiler and ask it to keep intermediate assembler code.

Then use diff to see if the assembler files differ.

On FreeBSD with clang, on an x86_64 architecture, you can check that both of the files are strictly the same. The pre-increment is done the same way as the post-increment: addl $1, %eax.

Create x.c:

int main() {
  for(int i=0;i<100;++i){}
}

Compile it:

% cc -S x.c
%

look at the code:

        .file   "x.c"
        .text
        .globl  main
        .align  16, 0x90
        .type   main,@function
main:                                   # @main
        .cfi_startproc
# BB#0:
        pushq   %rbp
.Ltmp2:
        .cfi_def_cfa_offset 16
.Ltmp3:
        .cfi_offset %rbp, -16
        movq    %rsp, %rbp
.Ltmp4:
        .cfi_def_cfa_register %rbp
        movl    $0, -4(%rbp)
        movl    $0, -8(%rbp)
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        cmpl    $100, -8(%rbp)
        jge     .LBB0_4
# BB#2:                                 #   in Loop: Header=BB0_1 Depth=1
        jmp     .LBB0_3
.LBB0_3:                                #   in Loop: Header=BB0_1 Depth=1
        movl    -8(%rbp), %eax
        addl    $1, %eax
        movl    %eax, -8(%rbp)
        jmp     .LBB0_1
.LBB0_4:
        movl    -4(%rbp), %eax
        popq    %rbp
        ret
.Ltmp5:
        .size   main, .Ltmp5-main
        .cfi_endproc


        .ident  "FreeBSD clang version 3.4.1 (tags/RELEASE_34/dot1-final 208032) 20140512"
        .section        ".note.GNU-stack","",@progbits

Do the same with --i instead of ++i.