Java for loop performance question

前端 未结 13 1205
长发绾君心
长发绾君心 2020-12-15 05:17

considering this example:

public static void main(final String[] args) {
    final List myList = Arrays.asList(\"A\", \"B\", \"C\", \"D\");
            


        
13条回答
  •  半阙折子戏
    2020-12-15 05:34

    Note that the javac compiler has about nothing to do with optimization. The "important" compiler is the JIT compiler which lives within the JVM.

    In your example, in the most generic case, the myList.size() is a simple method dispatch, which returns the contents of a field in the List instance. This is negligible work compared to what is implied by System.out.println("Hello") (at least one system call, hence hundreds of clock cycles, compared to no more than a dozen for the method dispatch). I very much doubt that your code could exhibit a meaningful difference in speed.

    On a more general basis, the JIT compiler should recognize this call to size() as a call to a known instance, so that it may perform the method dispatch with a direct function call (which is faster), or even inline the size() method call, reducing the call to a simple instance field access.

提交回复
热议问题