writing fast loop?

Dear all,

There are many ways to write a for loop:

mov ecx, maxValue

loop: _StartOfLoop

xor eax,eax


add eax,1
cmp eax, maxValue
jnl _StartOfLoop

mov ecx, maxValue

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.

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.

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

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

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

Experts Exchange Solution brought to you by

Your issues matter to us.

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

Start your 7-day free trial
>  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
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

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.