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.

10
  • 4
    In theory, version 2 is more efficient, but in practise it should be negligible. Commented Mar 28, 2018 at 16:02
  • 1
    @Alnitak Why version 2? Commented Mar 28, 2018 at 16:03
  • 1
    I think the second one is more efficient since it avoid to allocate memory for a variable, affect it and then read it. But maybe the compiler is able to detect that res is useless and compile the same for both solution Commented Mar 28, 2018 at 16:03
  • 1
    what about static String function2(int x) { return x > 10 ? "a" : "b";} Commented Mar 28, 2018 at 16:05
  • function2 is more efficient, check on one condition and have no variables. but the code is simple compiler can't notice the difference. Commented Mar 28, 2018 at 16:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

2 Comments

"" is interned (as a string literal), so no redundant empty string will be actually created.
@lexicore The code will add the empty string to the intern pool, so it is created by the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.