String对象有个特殊的StringTable字符串常量池,为了减少Heap中生成的字符串的数量,推荐尽量直接使用String Table中的字符串常量池中的元素。
public native String intern();
还是用JMH工具来进行性能分析,我们使用String.intern,HashMap,和ConcurrentHashMap来对比分析,分别调用1次,100次,10000次和1000000。
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, jvmArgsPrepend = "-XX:+PrintStringTableStatistics")
@Warmup(iterations = 5)
@Measurement(iterations = 5)
public class StringInternBenchMark {
@Param({"1", "100", "10000", "1000000"})
private int size;
private StringInterner str;
private ConcurrentHashMapInterner chm;
private HashMapInterner hm;
@Setup
public void setup() {
str = new StringInterner();
chm = new ConcurrentHashMapInterner();
hm = new HashMapInterner();
}
public static class StringInterner {
public String intern(String s) {
return s.intern();
}
}
@Benchmark
public void useIntern(Blackhole bh) {
for (int c = 0; c < size; c++) {
bh.consume(str.intern("doit" + c));
}
}
public static class ConcurrentHashMapInterner {
private final Map<String, String> map;
public ConcurrentHashMapInterner() {
map = new ConcurrentHashMap<>();
}
public String intern(String s) {
String exist = map.putIfAbsent(s, s);
return (exist == null) ? s : exist;
}
}
@Benchmark
public void useCurrentHashMap(Blackhole bh) {
for (int c = 0; c < size; c++) {
bh.consume(chm.intern("doit" + c));
}
}
public static class HashMapInterner {
private final Map<String, String> map;
public HashMapInterner() {
map = new HashMap<>();
}
public String intern(String s) {
String exist = map.putIfAbsent(s, s);
return (exist == null) ? s : exist;
}
}
@Benchmark
public void useHashMap(Blackhole bh) {
for (int c = 0; c < size; c++) {
bh.consume(hm.intern("doit" + c));
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(StringInternBenchMark.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
Benchmark (size) Mode Cnt Score Error Units
StringInternBenchMark.useCurrentHashMap 1 avgt 5 34.259 ± 7.191 ns/op
StringInternBenchMark.useCurrentHashMap 100 avgt 5 3623.834 ± 499.806 ns/op
StringInternBenchMark.useCurrentHashMap 10000 avgt 5 421010.654 ± 53760.218 ns/op
StringInternBenchMark.useCurrentHashMap 1000000 avgt 5 88403817.753 ± 12719402.380 ns/op
StringInternBenchMark.useHashMap 1 avgt 5 36.927 ± 6.751 ns/op
StringInternBenchMark.useHashMap 100 avgt 5 3329.498 ± 595.923 ns/op
StringInternBenchMark.useHashMap 10000 avgt 5 417959.200 ± 62853.828 ns/op
StringInternBenchMark.useHashMap 1000000 avgt 5 79347127.709 ± 9378196.176 ns/op
StringInternBenchMark.useIntern 1 avgt 5 161.598 ± 9.128 ns/op
StringInternBenchMark.useIntern 100 avgt 5 17211.037 ± 188.929 ns/op
StringInternBenchMark.useIntern 10000 avgt 5 1934203.794 ± 272954.183 ns/op
StringInternBenchMark.useIntern 1000000 avgt 5 418729928.200 ± 86876278.365 ns/op