什么功能更有效?

时间:2018-03-28 16:00:58

标签: java

我是Java的新手,我想知道这两个函数之间是否存在差异:

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

    return res;
}

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

    return "b";
}

我不是在谈论代码的长度,只是说效率。

2 个答案:

答案 0 :(得分:6)

理论上第二个版本更有效,反编译为:

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

而带有赋值的版本反编译为:

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

可以看到创建并返回附加变量。

然而在实践中,实际运行时性能的差异应该可以忽略不计。 JIT编译器(希望)会优化掉无用的变量,并且在任何情况下,除非代码根据您的分析器处于热代码路径中,否则这肯定会被视为过早优化。

答案 1 :(得分:0)

两个版本最终都会创建"a""b"字符串并将其返回。 但是版本2在效率方面更好,它不会在内存中创建冗余的空字符串""