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

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

问题描述

有两种类型的如果中的java语句 - 经典: if {} else {} 和简写: exp? value1:value2 。是一个比另一个更快还是相同?

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 语句。

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;
    }
}

Bytecode用 javap反编译 - c测试

Bytecode decompiled with 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天全站免登陆