Ho provato due esempi come da te per la tua domanda. Su questa base devo dire che il secondo approccio sarebbe meglio. (Anche se io non sto considerando Multi-Threading)
Test.java
public class Test{
public static void main(String... args){
String[][] arr2 = new String[5][5];
for (final String[] obj : arr2)
{
for (final String str : obj)
System.out.println(str.length() +" " + obj.length);
}
}
}
dopo la compilazione e poi di nuovo la decompilazione ho ottenuto questo.
* Decompiled with CFR 0_114.
*/
import java.io.PrintStream;
public class Test {
public static /* varargs */ void main(String ... arrstring) {
String[][] arrstring2;
String[][] arrstring3 = arrstring2 = new String[5][5];
int n = arrstring3.length;
for (int i = 0; i < n; ++i) {
String[] arrstring4;
for (String string : arrstring4 = arrstring3[i]) { //assignment will take place m*n.
System.out.println("" + string.length() + " " + arrstring4.length);
//this arrstring4.length will execute m*n (in this case).So, this will less efficient than others.
}
}
}
}
Test1.java
public class Test1{
public static void main(String... args){
String[][] arr2 = new String[5][5];
for (final String[] obj : arr2)
{
int value = obj.length;
for (final String str : obj)
System.out.println(str.length() +" " + value);
}
}
}
dopo la compilazione e poi di nuovo la decompilazione ho ottenuto questo.
/*
* Decompiled with CFR 0_114.
*/
import java.io.PrintStream;
public class Test1 {
public static /* varargs */ void main(String ... arrstring) {
String[][] arrstring2;
for (String[] arrstring3 : arrstring2 = new String[5][5]) {
int n = arrstring3.length; //Assignment will take place M times only.
//this will calculate M times only. So, it will definitely faster than above.
for (String string : arrstring3) {
System.out.println("" + string.length() + " " + n);
//here n is calculate M times but can be printed M*N times.
}
}
}
}
fonte
2016-05-16 12:15:28
di lavoro per lo studente: compilare entrambe le versioni e confrontare l'output bytecode. Ecco un riferimento; https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html – DwB
Beh, non penso che questa domanda sia una domanda a livello di studenti ma vabbè mi stavo chiedendo se qualcuno già conosce la risposta a questo invece di dirmi che è possibile guardare il bytecode di output, che so che potrei. e anche, dovrei guardare le uscite per Android. questo può essere un diavolo di un progetto per rispondere a questa domanda da solo. –
Il compilatore può sapere che 'a.bar()' restituirà sempre lo stesso valore per un dato 'a'? –