由于速度差异,我错过了一些数字。因此,我尝试对它们进行基准测试,结果并非如此简单:在某些运行/ JIT的错误之后,Java循环变慢了?
我最终使用了Caliper,结果与手动运行测试的结果相同:
静态/动态调用没有可测量的差异。至少不适用于Linux / AMD64 / Java7。
卡尺结果在这里:https ://microbenchmarks.appspot.com/runs/1426eac9-36ca-48f0-980f-0106af064e8f#r:scenario.benchmarkSpec.methodName,scenario.vmSpec.options.CMSLargeCoalSurplusPercent,scenario.vmSpec.options 。 CMSLargeSplitSurplusPercent,scenario.vmSpec.options.CMSSmallCoalSurplusPercent,scenario.vmSpec.options.CMSSmallSplitSurplusPercent,scenario.vmSpec.options.FLSLargestBlockCoalesceProximity,scenario.vmSpec.OptionsSteps.G1Conc
我自己的结果是:
Static: 352 ms
Dynamic: 353 ms
Static: 348 ms
Dynamic: 349 ms
Static: 349 ms
Dynamic: 348 ms
Static: 349 ms
Dynamic: 344 ms
卡尺测试课程为:
public class TestPerfomanceOfStaticMethodsCaliper extends Benchmark {
public static void main( String [] args ){
CaliperMain.main( TestPerfomanceOfStaticMethodsCaliper.class, args );
}
public int timeAddDynamic( long reps ){
int r=0;
for( int i = 0; i < reps; i++ ) {
r |= addDynamic( 1, i );
}
return r;
}
public int timeAddStatic( long reps ){
int r=0;
for( int i = 0; i < reps; i++ ) {
r |= addStatic( 1, i );
}
return r;
}
public int addDynamic( int a, int b ){
return a+b;
}
private static int addStatic( int a, int b ){
return a+b;
}
}
我自己的Test类是:
public class TestPerformanceOfStaticVsDynamicCalls {
private static final int RUNS = 1_000_000_000;
public static void main( String [] args ) throws Exception{
new TestPerformanceOfStaticVsDynamicCalls().run();
}
private void run(){
int r=0;
long start, end;
for( int loop = 0; loop<10; loop++ ){
// Benchmark
start = System.currentTimeMillis();
for( int i = 0; i < RUNS; i++ ) {
r += addStatic( 1, i );
}
end = System.currentTimeMillis();
System.out.println( "Static: " + ( end - start ) + " ms" );
start = System.currentTimeMillis();
for( int i = 0; i < RUNS; i++ ) {
r += addDynamic( 1, i );
}
end = System.currentTimeMillis();
System.out.println( "Dynamic: " + ( end - start ) + " ms" );
// Do something with r to keep compiler happy
System.out.println( r );
}
}
private int addDynamic( int a, int b ){
return a+b;
}
private static int addStatic( int a, int b ){
return a+b;
}
}