Pikolo
Pikolo

Reputation: 99

What function is more efficient?

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.

Upvotes: 0

Views: 100

Answers (2)

Alnitak
Alnitak

Reputation: 340055

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.

Upvotes: 6

hoan
hoan

Reputation: 1098

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.

Upvotes: 0

Related Questions