How is Java's for loop code generated by the compiler

前端 未结 4 1616
再見小時候
再見小時候 2020-12-06 04:57

How is Java\'s for loop code generated by the compiler?

For example, if I have:

for(String s : getStringArray() )
{
   //do something with s
}
         


        
4条回答
  •  青春惊慌失措
    2020-12-06 05:18

    JDK 1.4 introduced the RandomAccess interface. It is meant to give a hint to algorithms when, for a given List implementation, it is more efficient to iterate through:

    for (int i = 0, n = list.size(); i < n; i++) {
        list.get(i);
    }
    

    than

    for (Iterator i = list.iterator(); i.hasNext(); ) {
       i.next();
    }
    

    Does the foreach loop take this into account? Or does it completely ignore the fact that a given Iterable is in fact a List?

    It should be noted that this would imply that adding a (iterable instanceof List && iterable instanceof RandomAccess) test and a downcast to List would work, which would add an overhead that's not always worth it and could be considered a premature optimization for a compiler syntactic sugar feature.

提交回复
热议问题