gpt4 book ai didi

java - 静态空数组实例的性能优势

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:26 25 4
gpt4 key购买 nike

将常量空数组返回值提取到静态常量似乎是常见的做法。喜欢这里:

public class NoopParser implements Parser {
private static final String[] EMPTY_ARRAY = new String[0];

@Override public String[] supportedSchemas() {
return EMPTY_ARRAY;
}

// ...
}

大概这样做是出于性能原因,因为直接返回 new String[0] 会在每次调用该方法时创建一个新的数组对象——但真的会这样吗?

我一直想知道这样做是否真的有可衡量的性能优势,或者这是否只是过时的民间智慧。空数组是不可变的。 VM 是否无法将所有空的 String 数组合并为一个? VM 不能使 new String[0] 基本上免费吗?

将这种做法与返回空字符串进行对比:我们通常非常乐意编写 return "";,而不是 return EMPTY_STRING;

最佳答案

我使用 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 .

环境(见 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: <none>
# 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 默认开启(见于 java -XX:+PrintFlagsFinal -version | grep EliminateAllocations)

结果:

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

使用常量几乎快两倍。

关闭 EliminateAllocations 会稍微减慢速度。

关于java - 静态空数组实例的性能优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301251/

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