- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在调查一个方法的性能,并最终确定开销是由 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 为单位)
Mac 基准测试(以 nano 为单位)
最佳答案
你的测试是废话。如果我交换测试条件,我会得到完全相反的结果:
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/
我正在尝试学习Rust。我正在阅读一本书online,该书实现了unix程序cat。现在,我试图读取作为像cargo run file1.txt file2.txt这样的参数传递的文件的内容,但是程序
我在 GHC 8.0.1 中遇到了一个带有种类索引 (?) GADT 的奇怪情况,其中在类型与种类签名中引入 foralls 会产生不同的类型检查行为。 考虑以下数据类型: {-# LANGUAGE
我正在使用 Perl 5.10 开发应用程序,HTML::Mason和 Apache 2.2。这是我第一次在大型项目中使用 Perl 5.10。我每隔一段时间就会出现奇怪的行为。应用程序因一个非常奇怪
我正在尝试将文件上传到aws中的rust中,因为我使用的是 rusoto_s3 的s3 rust客户端,当这些部分从单个线程发送时,我设法使分段上传代码正常工作不是我想要的,我想上传大文件,并且希望能
我是一名优秀的程序员,十分优秀!