-3

While coding, I was just curious if there is a difference in terms of performace between two codes.

for(int i=0;i<10;i++){
   if(i>-1)
      printf("Bigger! than -1");
   if(i>5)
      printf("Bigger! than 5");
}

vs

for(int i=0;i<10;i++)
   if(i>-1)
      printf("Bigger! than -1");
for(int i=0;i<10;i++)
   if(i>5)
      printf("Bigger! than 5");


Is there any performance difference and if there is, what are the factors that make those difference?

shapeless
  • 175
  • 1
  • 10
  • In the first version you're dong only one loop (10 iterations), the second your doing a 2 loops (20 iterations). Theoretically the second one is worse but they are both o(n) https://stackoverflow.com/questions/25777714/which-algorithm-is-faster-on-or-o2n – LorenzOliveto Apr 12 '19 at 15:26
  • Just look at the assembly code to see if your compiler generate different code. gcc main.c -S – Robert Apr 12 '19 at 15:45
  • it certainly does generate different machine code. The output of the first one is different from the second. – Michael Feldmeier Apr 12 '19 at 15:51

1 Answers1

3

Not enough reputation to comment, hence writing this as an answer.

@Carcigenicate Since the output of both programs is different, they will certainly not be optimized to the same machine code.

I suspect the second version to be slower, as there are twice as many "write"-accesses to the memory for the index variable (and several more "read"-accesses).