Java for loop performance question

前端 未结 13 1194
长发绾君心
长发绾君心 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:39

    In cases of "compiler optimization", the best you can do is for-each loops:

    for(final String x : myList) { ... }
    

    Which lets the compiler provide the fastest implementation.

    Edit:

    The difference between your code examples is in the second argument of the for-loop. In the first example, the VM will do a method call (more expensive) and is thus slower (only significant when there are a lot of iterations). In your second example, the VM will do a stack pop (less expensive, and local variables are on the stack), and thus faster (only significant when there are a lot of iterations: for just one iteration, the first one is faster, in terms of memory usage).

    Also: "Premature optimization is the root of all evil." Donald Knuth's infamous law.

提交回复
热议问题