0

I'm new to Java and i wanted to know if there is a difference between these 2 functions:

public static String function1(int x) {
    String res = "";
    if(x > 10)
        res = "a";
    else
        res = "b";

    return res;
}

and:

public static String function2(int x) {
    if(x > 10)
        return "a";

    return "b";
}

and I'm not speaking on the length of the code, only efficiency.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
Pikolo
  • 99
  • 1
  • 3
  • 11

2 Answers2

6

The second version is in theory more efficient, decompiling to:

public static java.lang.String function1(int);
Code:
   0: ldc           #2                  // String
   2: astore_1
   3: iload_0
   4: bipush        10
   6: if_icmple     12
   9: ldc           #3                  // String a
  11: areturn
  12: ldc           #4                  // String b
  14: areturn

whereas the version with the assignment decompiles to:

public static java.lang.String function1(int);
Code:
   0: ldc           #2                  // String
   2: astore_1
   3: iload_0
   4: bipush        10
   6: if_icmple     15
   9: ldc           #3                  // String a
  11: astore_1
  12: goto          18
  15: ldc           #4                  // String b
  17: astore_1
  18: aload_1
  19: areturn

where it can be seen that the additional variable is created and returned.

However in practise the difference in actual runtime performance should be negligible. The JIT compiler would (hopefully) optimise away the useless variable, and in any case unless the code was in a hot code path according to your profiler then this would certainly count as premature optimisation.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • I was just writing this exact answer. For the benefit of the OP, the bytecode was obtained by compiling a class containing these methods using `javac ClassName.java` then running `javap -c ClassName`. – bcsb1001 Mar 28 '18 at 16:13
0

Both versions end up creating a string either "a" or "b" and return it out. But version 2 is better in term of efficiency, which doesn't create an redundant empty string "" in memory.

hoan
  • 1,058
  • 8
  • 13