java - Does JVM create an iterator when it iterates over array with for-each loop? -
sorry if asked, did not find answer on stackoveflow , didn't see official tutorials field.
the question in title - if have code like
int[] array = new int[20]; (int el : array) { ... }
will jvm run standard loop
for (int = 0; < array.length; i++)
or create iterator?
upd link may helpful complete answer
fastest way iterate array in java: loop variable vs enhanced statement
arrays in java don't implement iterable interface cannot iterator array. cannot have iterator on primitive types such int because primitive type can't generic parameter. e.g. if want iterator, have use iterator instead, result in lot of autoboxing , -unboxing if that's backed int[].
the jvm unlikely create iterator for-each loop on arrays inefficient.
in fact compiler transform for-each loop indexed loop. can check viewing decompiled byte code method:
source code:
public void test() { int[] array = new int[20]; (int el : array) { system.out.println("test"); } }
decompiled byte-code:
public void test() { int[] array = new int[20]; int[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { int var10000 = var2[var4]; system.out.println("lol"); } }
Comments
Post a Comment