to use if or not to

i was just playing around with the idea of not using if statement and decided to do a program which outputs the number of factors a number has
"10 has four factors 1,2,5,10" and did two programs
for(int x=1; x<=n; x++)

for(int x=1; x<=n; x++)

the one using if statement is way faster then the first one
just wondering your opinion and explanation for this =)
The latter is faster because it uses 5 less arithmetic operations than the former per loop.
When computing the number of factors of 'n', the second uses n arithmetic operations, while the first uses 6n operations. It doesn't have anything to do with the if statement.

I went and tested it out by looking at the disassembly, the first generates this:
0x100002890:  movl   $1, -28(%rbp)
0x100002897:  movl   -28(%rbp), %eax
0x10000289a:  cmpl   -20(%rbp), %eax
0x10000289d:  jg     0x1000028de  
0x1000028a3:  movl   -20(%rbp), %eax
0x1000028a6:  movl   -28(%rbp), %ecx
0x1000028a9:  movl   %eax, -32(%rbp)
0x1000028ac:  cltd   
0x1000028ad:  idivl  %ecx
0x1000028af:  movl   -32(%rbp), %eax
0x1000028b2:  decl   %eax
0x1000028b4:  movl   %edx, -36(%rbp)
0x1000028b7:  cltd   
0x1000028b8:  idivl  %ecx
0x1000028ba:  movl   -36(%rbp), %eax
0x1000028bd:  subl   %edx, %eax
0x1000028bf:  negl   %ecx
0x1000028c1:  decl   %eax
0x1000028c3:  cltd   
0x1000028c4:  idivl  %ecx
0x1000028c6:  movl   -24(%rbp), %ecx
0x1000028c9:  addl   %eax, %ecx
0x1000028cb:  movl   %ecx, -24(%rbp)
0x1000028ce:  movl   -28(%rbp), %eax
0x1000028d1:  addl   $1, %eax
0x1000028d6:  movl   %eax, -28(%rbp)
0x1000028d9:  jmpq   0x100002897 

the second generates this:
0x1000028a0:  movl   $1, -28(%rbp)
0x1000028a7:  movl   -28(%rbp), %eax
0x1000028aa:  cmpl   -20(%rbp), %eax
0x1000028ad:  jg     0x1000028e8
0x1000028b3:  movl   -20(%rbp), %eax
0x1000028b6:  movl   -28(%rbp), %ecx
0x1000028b9:  cltd   
0x1000028ba:  idivl  %ecx
0x1000028bc:  cmpl   $0, %edx
0x1000028c2:  jne    0x1000028d3   
0x1000028c8:  movl   -24(%rbp), %eax
0x1000028cb:  addl   $1, %eax
0x1000028d0:  movl   %eax, -24(%rbp)
0x1000028d3:  jmpq   0x1000028d8 
0x1000028d8:  movl   -28(%rbp), %eax
0x1000028db:  addl   $1, %eax
0x1000028e0:  movl   %eax, -28(%rbp)
0x1000028e3:  jmpq   0x1000028a7

You can see that the second uses way fewer operations to complete.

Note: Amount of assembly generated isn't always a good measure for how long a program takes to execute; but generally when designing algorithms you want to use the absolute minimum amount of clock cycles to complete the task.
Last edited on
Topic archived. No new replies allowed.