哪个“如果"构造更快 - 语句或三元运算符? [英] Which "if" construct is faster - statement or ternary operator?

查看:26
本文介绍了哪个“如果"构造更快 - 语句或三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java 中有两种类型的 if 语句 - 经典:if {} else {} 和简写:exp ?值1:值2.一个比另一个快还是相同?

There are two types of if statements in java - classic: if {} else {} and shorthand: exp ? value1 : value2. Is one faster than the other or are they the same?

声明:

int x;
if (expression) {
  x = 1;
} else {
  x = 2;
}

三元运算符:

int x = (expression) ? 1 : 2;

推荐答案

那里只有一种类型的if"语句.另一种是条件表达式.至于哪个性能更好:它们可以编译为相同的字节码,我希望它们的行为相同 - 或者非常接近以至于您绝对不想在性能方面选择一个.

There's only one type of "if" statement there. The other is a conditional expression. As to which will perform better: they could compile to the same bytecode, and I would expect them to behave identically - or so close that you definitely wouldn't want to choose one over the other in terms of performance.

有时 if 语句会更易读,有时条件运算符会更易读.特别是,当两个操作数简单且无副作用时,我建议使用条件运算符,而如果两个分支的主要目的 是它们的副作用,我可能会使用if 语句.

Sometimes an if statement will be more readable, sometimes the conditional operator will be more readable. In particular, I would recommend using the conditional operator when the two operands are simple and side-effect-free, whereas if the main purpose of the two branches is their side-effects, I'd probably use an if statement.

这是一个示例程序和字节码:

Here's a sample program and bytecode:

public class Test {
    public static void main(String[] args) {
        int x;
        if (args.length > 0) {
            x = 1;
        } else {
            x = 2;
        }
    }

    public static void main2(String[] args) {
        int x = (args.length > 0) ? 1 : 2;
    }
}

使用javap -c Test反编译的字节码:

public class Test extends java.lang.Object {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1
       4: return

  public static void main(java.lang.String[]
    Code:
       0: aload_0
       1: arraylength
       2: ifle          10
       5: iconst_1
       6: istore_1
       7: goto          12
      10: iconst_2
      11: istore_1
      12: return

  public static void main2(java.lang.String[
    Code:
       0: aload_0
       1: arraylength
       2: ifle          9
       5: iconst_1
       6: goto          10
       9: iconst_2
      10: istore_1
      11: return
}

如您所见,这里的字节码存在轻微差异 - 无论 istore_1 是否出现在 brance 中(与我之前存在巨大缺陷的尝试不同:)但如果 JITter 最终使用不同的本机代码,我会感到非常惊讶.

As you can see, there is a slight difference in bytecode here - whether the istore_1 occurs within the brance or not (unlike my previous hugely-flawed attempt :) but I would be very surprised if the JITter ended up with different native code.

这篇关于哪个“如果"构造更快 - 语句或三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆