consider the following :
1.
for (final Bar a : bars) {
for (final Foo f : foos) {
doSomethingWith(f.foo(), a.bar());
}
}
and :
2.
for (final Bar a : bars) {
final Object bar = a.bar();
for (final Foo f : foos) {
doSomethingWith(f.foo(), bar);
}
}
Is this kind of optimization really helpfull or will the compiler do it automatically anyway?
Will your answer change if bar() was a getter? (e.g getBar())
Will your answer change if i am targeting Android development?
I have tried two examples as per you doing for your question. On this basis I must say Second Approach would be better. (Although I am not considering 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);
}
}
}
after compiling and then again decompiling I got this.
* 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);
}
}
}
after compiling and then again decompiling I got this.
/*
* 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.
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With