私はメソッドのパフォーマンスを調査しており、最終的にオーバーヘッドが 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
ます。
1.6 の最新ビルドを使用して、Mac と Linux Java の両方でこれを実行しました。一貫して、条件のためにelse部分が決して実行されないようにコードが構造化されているにもかかわらず、elseセクションがない最初のベンチマークは、elseセクションのある2番目のベンチマークよりもはるかに高速です。一部の人にとって、違いは重要ではないかもしれませんが、相対的なパフォーマンスの違いは大きいことを理解しています. 誰かがこれについて何か洞察を持っているのだろうか(または、私が間違ったことをしたのかもしれません)。
Linux ベンチマーク (nano)
- パフォーマンス 1215488
- パフォーマンス 2629531
Mac ベンチマーク (nano)
- パフォーマンス 1667000
- パフォーマンス 4208000