Performance benefits of a static empty array instance

前端 未结 4 1659
夕颜
夕颜 2020-12-11 17:47

It seems common practice to extract a constant empty array return value into a static constant. Like here:

public class NoopParser implements Parser {
    pr         


        
4条回答
  •  天命终不由人
    2020-12-11 18:26

    I benchmarked it using JMH:

    private static final String[] EMPTY_STRING_ARRAY = new String[0];
    
    @Benchmark
    public void testStatic(Blackhole blackhole) {
        blackhole.consume(EMPTY_STRING_ARRAY);
    }
    
    @Benchmark
    @Fork(jvmArgs = "-XX:-EliminateAllocations")
    public void testStaticEliminate(Blackhole blackhole) {
        blackhole.consume(EMPTY_STRING_ARRAY);
    }
    
    @Benchmark
    public void testNew(Blackhole blackhole) {
        blackhole.consume(new String[0]);
    }
    
    @Benchmark
    @Fork(jvmArgs = "-XX:-EliminateAllocations")
    public void testNewEliminate(Blackhole blackhole) {
        blackhole.consume(new String[0]);
    }
    
    @Benchmark
    public void noop(Blackhole blackhole) {
    }
    

    Full source code.

    Environment (seen after java -jar target/benchmarks.jar -f 1):

    # JMH 1.11.2 (released 51 days ago)
    # VM version: JDK 1.7.0_75, VM 24.75-b04
    # VM invoker: /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
    # VM options: 
    # Warmup: 20 iterations, 1 s each
    # Measurement: 20 iterations, 1 s each
    # Timeout: 10 min per iteration
    # Threads: 1 thread, will synchronize iterations
    # Benchmark mode: Throughput, ops/time
    

    EliminateAllocations was on by default (seen after java -XX:+PrintFlagsFinal -version | grep EliminateAllocations).

    Results:

    Benchmark                         Mode  Cnt           Score         Error  Units
    MyBenchmark.testNewEliminate     thrpt   20    95912464.879 ± 3260948.335  ops/s
    MyBenchmark.testNew              thrpt   20   103980230.952 ± 3772243.160  ops/s
    MyBenchmark.testStaticEliminate  thrpt   20   206849985.523 ± 4920788.341  ops/s
    MyBenchmark.testStatic           thrpt   20   219735906.550 ± 6162025.973  ops/s
    MyBenchmark.noop                 thrpt   20  1126421653.717 ± 8938999.666  ops/s
    

    Using a constant was almost two times faster.

    Turning off EliminateAllocations slowed things down a tiny bit.

提交回复
热议问题