哪个“如果”是构造更快 - 语句还是三元运算符?

发布于 2024-10-12 03:58:54 字数 276 浏览 2 评论 0原文

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

语句:

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

三元运算符:

int x = (expression) ? 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?

statement:

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

ternary operator:

int x = (expression) ? 1 : 2;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

帥小哥 2024-10-19 03:58:54

那里只有一种类型的“if”语句。另一种是条件表达式。至于哪个性能更好:它们可以编译为相同的字节码,并且我希望它们的行为相同 - 或者如此接近,以至于您肯定不想在性能方面选择一个而不是另一个。

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

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

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< /code> 是否出现在括号内(与我之前有巨大缺陷的尝试不同:),但如果 JITter 最终得到不同的本机代码,我会感到非常惊讶。

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.

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

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.

命硬 2024-10-19 03:58:54

您的两个示例可能会编译为相同或几乎相同的字节码,因此性能应该没有差异。

如果执行速度存在差异,您仍然应该使用最惯用的版本(第二个版本用于根据简单条件和两个简单​​子表达式分配单个变量,第一个版本用于执行更复杂的操作或不适合单行的操作)。

Both of your examples will probably compile to identical or nearly identical bytecode, so there should be no difference in performance.

Had there been a difference in execution speed, you should still use the most idiomatic version (which would be the second one for assigning a single variable based on a simple condition and two simple sub-expressions, and the first one for doing more complex operations or operations that do not fit on a single line).

心碎的声音 2024-10-19 03:58:54

这些是相同的。它们都相当快,通常约为 10-30 纳秒。 (取决于使用模式)这个时间范围对您来说重要吗?

你应该做你认为最清楚的事情。

These are the same. Both of them are fairly fast, typically around 10-30 nano-seconds. (depending on usage pattern) Is this time frame important to you?

You should do what you believe is clearest.

-残月青衣踏尘吟 2024-10-19 03:58:54

只是添加到所有其他答案:

第二个表达式通常称为三元/三元运算符/语句。它非常有用,因为它返回一个表达式。有时,它使典型的简短语句的代码更加清晰。

Just to add to all the other answers:

The second expression is often called tertiary/ternary operator/statement. It can be very useful because it returns an expression. Sometimes it makes the code more clearer for typical short statements.

画骨成沙 2024-10-19 03:58:54

两者都不是 - 它们将被编译为相同的。

neither - they will be compiled to the same.

治碍 2024-10-19 03:58:54

三元运算符比 if-else 条件更快。

public class TerinaryTest {
    public static void main(String[] args)
    {
        int j = 2,i = 0;
        Date d1 = new Date();
        for(long l=1;l<100000000;l++)
            if(i==1) j=1;
                else j=0;
        Date d2 = new Date();
        for(long l=1;l<100000000;l++)
            j=i==1?1:0;
        Date d3 = new Date();
        System.out.println("Time for if-else: " + (d2.getTime()-d1.getTime()));
        System.out.println("Time for ternary: " + (d3.getTime()-d2.getTime()));
    }
}

测试结果:

Trail-1:

if-else 时间:63

三元时间:31

Trail-2:

if-else 时间:78

三元时间:47

Trail-3:

if-else 时间:94

三元时间: 31

Trail-4:

if-else 时间:78

三元时间:47

Ternary operator is faster than if-else condition.

public class TerinaryTest {
    public static void main(String[] args)
    {
        int j = 2,i = 0;
        Date d1 = new Date();
        for(long l=1;l<100000000;l++)
            if(i==1) j=1;
                else j=0;
        Date d2 = new Date();
        for(long l=1;l<100000000;l++)
            j=i==1?1:0;
        Date d3 = new Date();
        System.out.println("Time for if-else: " + (d2.getTime()-d1.getTime()));
        System.out.println("Time for ternary: " + (d3.getTime()-d2.getTime()));
    }
}

Test Results:

Trail-1:

Time for if-else: 63

Time for ternary: 31

Trail-2:

Time for if-else: 78

Time for ternary: 47

Trail-3:

Time for if-else: 94

Time for ternary: 31

Trail-4:

Time for if-else: 78

Time for ternary: 47

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文