gpt4 book ai didi

java - 对 java if else 性能感到困惑

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:29:47 27 4
gpt4 key购买 nike

我正在调查一个方法的性能,并最终确定开销是由 if else 语句的“else”部分引起的。我编写了一个小程序来说明即使代码的 else 部分从未执行时的性能差异:

public class TestIfPerf
{
public static void main( String[] args )
{
boolean condition = true;
long time = 0L;
int value = 0;
// warm up test
for( int count=0; count<10000000; count++ )
{
if ( condition )
{
value = 1 + 2;
}
else
{
value = 1 + 3;
}
}
// benchmark if condition only
time = System.nanoTime();
for( int count=0; count<10000000; count++ )
{
if ( condition )
{
value = 1 + 2;
}
}
time = System.nanoTime() - time;
System.out.println( "1) performance " + time );
time = System.nanoTime();
// benchmark if else condition
for( int count=0; count<10000000; count++ )
{
if ( condition )
{
value = 1 + 2;
}
else
{
value = 1 + 3;
}
}
time = System.nanoTime() - time;
System.out.println( "2) performance " + time );
}
}

并使用 java -classpath 运行测试程序。 -Dmx=800m -Dms=800m TestIfPerf.

我在 Mac 和 Linux Java 上使用 1.6 最新版本执行了此操作。一致地,没有 else 的第一个基准测试比带有 else 部分的第二个基准测试快得多,即使代码的结构使得 else 部分永远不会因为条件而执行。我知道对某些人来说,差异可能并不显着,但相对性能差异很大。我想知道是否有人对此有任何见解(或者我做错了什么)。


Linux 基准测试(以 nano 为单位)

  1. 表现 1215488
  2. 性能 2629531

Mac 基准测试(以 nano 为单位)

  1. 性能 1667000
  2. 性能 4208000

最佳答案

你的测试是废话。如果我交换测试条件,我会得到完全相反的结果:

1) performance 5891113
2) performance 15216601

2) performance 5428062
1) performance 15087676

这可能与 JVM 在执行过程中优化代码有关。如果我多次复制/粘贴条件,我会得到:

2) performance 6258694
1) performance 34484277
2) performance 978
1) performance 978
2) performance 908

关于java - 对 java if else 性能感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13896787/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com