Is it slower to iterate through a list in Java like this:
for (int i=0;i<list.size();i++) {
.. list.get(i)
}
as opposed to:
for (Object o: list) {
... o
}
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.
I believe that once your code gets compiled, it doesn’t make a difference. It does make a difference before (example 2 is a lot more readable and concise), so go for number 2 and do not care about the rest.
Just my 2 cents
EDIT
Note your code in snippet number 1 calculates
list.size()every time the loop runs, that could make it even slower than number 2YET ANOTHER EDIT
Something I had to double check, Joshua Bloch recommends using
for eachloops (see item 46 of Effective Java). I believe that ends all kinds of discussions. Thanks Josh! 🙂