title: Using collection size in for loop comparison
body: <p>Is there a compiler optimization for the size() methods of Collections in Java? </p>
  
  <p>Consider the following code:    </p>
  
  <pre><code>for(int i=0;i&lt;list.size();i++)
        ...some operation.....
  </code></pre>
  
  <p>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).</p>
  
  <pre><code>final int len = list.size()
  for(int i=0;i&lt;len;i++)
        ...some operation.....
  </code></pre>
  
  <p>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?</p>
  
  <p><strong>Update1:</strong> 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)? </p>
  
  <p><strong>Update 2:</strong> 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.</p>