# writing fast loop?

Dear all,

There are many ways to write a for loop:
for(i=0;i<maxValue<i++){
....
}
Eg)

mov ecx, maxValue
_StartOfLoop:

....
loop: _StartOfLoop

----------------------------
xor eax,eax
_StartOfLoop:

...

cmp eax, maxValue
jnl _StartOfLoop

----------------------------
mov ecx, maxValue
_StartOfLoop:

....
djnz: _StartOfLoop

----------------------------

My Questions are:
1) Is there any other ways that I have missed out?
2)which is the fastest and why? (assume that the value of the counter i would be used in calculation)

thank you.

###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
If you count down to zero you don't need a cmp instruction.

The loop instruction is slower than an explicit "dec ecx; jnz" pair on quite a few CPU's.

You can minimize the loop overhead by repeating the code inside the loop a few times and adjusting the loop count.

0
Commented:
Assume maxValue is an immediate value, and assume this code run on 486
mov ecx, maxValue                  ; 1 clocks
_StartOfLoop:
....
loop: _StartOfLoop                   ; 6 Clocks
so this mathod is 7 clocks

xor eax,eax                             ; 1 clock
_StartOfLoop:
...
cmp eax, maxValue                 ; 1 clock
jnl _StartOfLoop                      ; 3 clocks
this method is 6 clocks

mov ecx, maxValue                  ; 1 clock
_StartOfLoop:
....
dec ecx                                   ; 1 clock
djnz: _StartOfLoop                  ; 3 clocks
this method is 5 clocks
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
>  You can minimize the loop overhead by repeating the code inside the loop a few times and adjusting the loop count.
Up to the size of your instruction cache
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Assembly

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.