I have an List with one element in it, but which may have more later. The list I am using is an ArrayList. I find that by calling List.get(0) instead of using a for loop I get faster results. Why is this? Shouldn’t looping over 1 item be the same as getting 1 item? If not then how can I get similar performance? I know that my array will eventually be larger than one item. I am using this loop in the body of a opengl renderer. When I use the loop my fps drops by 45.
Edit: I have fixed the problem. My renderer was adding a new value to the list each time it was rendered.
Using the enhanced for loop (for-each) in Java results in compiled code that works like this:
You were probably expecting it to be equivalent to this ?
but this is not the case, and constructing the iterator takes additional time that you are observing.