what is faster - for or foreach?

i want to check all elements inside an array if (whatever(arrayelement))
i know foreach creates an iterator, but how does it work for an array? if performance is very important, should i use the old style for loop?

1 comment
Comment actions Permalink

The performance of foreach for arrays is kind of optimal if jit is not dumb enough which is probably true. Let's consider the example java code:
void foo(Integer[] is) {
  for (Integer i : is) { 
   System.out.println(i);
  }
}

The output of javap is:
void foo(java.lang.Integer[]);
  Code:
   0:    aload_1 // load parameter on stack
   1:    astore_2 // store as a local variable, will be coalesced with the previous instruction into single register load when jit-compiled
   2:    aload_2 // load the local variable from stack, will be no-op
   3:    arraylength // assuming the variable on top of  the stack is of the array type, get its length
   4:    istore_3 // store array length into local
   5:    iconst_0 // push constant 0 onto stack
   6:    istore    4 // store into local
   8:    iload    4 // load local, will be no-op since it is already in the register
   10:    iload_3 // load array length, should be no-op, since it is already in the register
   11:    if_icmpge    34 //compare and branch to return when reached the end of the array
   14:    aload_2 // load the address of the array
   15:    iload    4 // load index
   17:    aaload // load the element of the array with given index.
   ....
   34:    return

0

Please sign in to leave a comment.