a) for(int i = 100000; i > 0; i--) {}
b) for(int i = 1; i < 100001; i++) {}
The answer is there on this website (question 3). I just can’t figure out why? From website:
3. a
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you get down to the lowest level (machine code but I’ll use assembly since it maps one-to-one mostly), the difference between an empty loop decrementing to 0 and one incrementing to 50 (for example) is often along the lines of:
That’s because the zero flag in most sane CPUs is set by the decrement instruction when you reach zero. The same can’t usually be said for the increment instruction when it reaches 50 (since there’s nothing special about that value, unlike zero). So you need to compare the register with 50 to set the zero flag.
However, asking which of the two loops:
is faster (in pretty much any environment, Java or otherwise) is useless since neither of them does anything useful. The fastest version of both those loops no loop at all. I challenge anyone to come up with a faster version than that 🙂
They’ll only become useful when you start doing some useful work inside the braces and, at that point, the work will dictate which order you should use.
For example if you need to count from 1 to 100,000, you should use the second loop. That’s because the advantage of counting down (if any) is likely to be swamped by the fact that you have to evaluate
100000-iinside the loop every time you need to use it. In assembly terms, that would be the difference between:(
dswis, of course, the infamousdo something withassembler mnemonic).Since you’ll only be taking the hit for an incrementing loop once per iteration, and you’ll be taking the hit for the subtraction at least once per iteration (assuming you’ll be using
i, otherwise there’s little need for the loop at all), you should just go with the more natural version.If you need to count up, count up. If you need to count down, count down.