Welcome to Questionaries, where you can ask questions and receive answers from other members of the community.

Let us know at info@questionaries.org

Is it faster to count down than it is to count up?

12 like 0 dislike
Hi guys,

Our computer science teacher once said that for some reason it is more efficient to count down that count up. For example if you need to use a FOR loop and the loop index is not used somewhere (like printing a line of N * to the screen) I mean that code like this :

for (i=N; i>=0; i--)  
  putchar('*');  

is better than:

for (i=0; i<N; i++)  
  putchar('*');  

Is it really true? and if so does anyone know why?
asked 2 years ago by biswaskeran (70,430 points)

1 Answer

0 like 0 dislike
In the Intel x86 instruction set, building a loop to count down to zero can usually be done with fewer instructions than a loop that counts up to a non-zero exit condition. Specifically, the ECX register is traditionally used as a loop counter in x86 asm, and the Intel instruction set has a special jcxz jump instruction that tests the ECX register for zero and jumps based on the result of the test.

However, the performance difference will be negligible unless your loop is already very sensitive to clock cycle counts. Counting down to zero might shave 4 or 5 clock cycles off each iteration of the loop compared to counting up, so it's really more of a novelty than a useful technique.

Also, a good optimizing compiler these days should be able to convert your count up loop source code into count down to zero machine code (depending on how you use the loop index variable) so there really isn't any reason to write your loops in strange ways just to squeeze a cycle or two here and there
answered 2 years ago by tulip (12,960 points)

Related questions

8 like 0 dislike
1 answer
11 like 3 dislike
3 answers
14 like 0 dislike
1 answer
9 like 0 dislike
1 answer
7 like 0 dislike
2 answers
asked 1 year ago by webmaster (25,380 points)