Is there a compiler optimization for the size() methods of Collections in Java?
Consider the following code:
for(int i=0;i<list.size();i++)
...some operation.....
There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).
final int len = list.size()
for(int i=0;i<len;i++)
...some operation.....
However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000. Am I missing something here?
Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?
Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.
See Question&Answers more detail:os