Possible Duplicate:
Which of these pieces of code is faster in Java?
If i write a loop as
for (int i=n; i>=0; i--)
And other one as
for (int i=0; i<=n; i++)
In java which one would be faster and why?..Say n=10000
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.
Never wonder; use Google Caliper to find out. Since there has been quite a bit of discussion around the relative weights of testing against zero vs. upper limit and incrementing vs. decrementing, here’s the Cartesian product of all these cases:
Results:
Apparently, whether the limit is zero or not has less effect than using inc vs. dec.
Let’s change it just a tiny bit…
To point out just how tenouous these differences are, here’s virtually the same code, but now it uses
longs (I include one method from the first example, to maintain scale):Results:
Main conclusion: never assume anything about performance at such a low level. Write your full code and test it as a whole because there will always be something else you are not taking into account, which completely turns the tables.