Java Map的最佳实践 - tremblay


今天的主题是关于Map我在许多代码评审中看到过的错误。
在Java 8中,添加了一些有用的新方法:

if (map.containsKey(key)) { // one hash
    return map.get(key);
// two hash
}
List<String> list = new ArrayList<>();
map.put(key, list);
// three hash
return list;

它也是最慢的。每次访问Map都会有哈希算法产生,目标是尽可能降低哈希,更好的方法是:

List<String> list = map.get(key); // one hash
if(list == null) {
    list = new ArrayList<>();
    map.put(key, list);
// two hash
}
return list;

只需要保存一个哈希。

重要提示:如果值null是可能无效,但我强烈建议你永远不要有空值。

但是从Java 8开始,你有三个更好的解决方案:
第一个是:

map.putIfAbsent(key, new ArrayList<>()); // one hash
return map.get(key);
// two hash

还会有两个哈希。而ArrayList需要被实例化,即使它已经在Map上。

可以用更长的代码来改进:

List<String> list = new ArrayList<>();
List<String> result = map.putIfAbsent(key, list); // one hash only!
if(result == null) {
    return list;
}
return result;

只有一个哈希!但ArrayList仍然有无用地实例化。

另一个Java 8方法来实现这一目标:

return map.computeIfAbsent(key, unused -> new ArrayList<>()); // one hash only!

任务完成。我们可以获得一行代码和最快的行。ArrayList在需要的时候将只实例化。

重要提示:不要这样做:map.computeIfAbsent(key, ArrayList::new)。 computeIfAbsent采用Function<KEY, VALUE>参数。因此,除非KEY匹配其中一个ArrayList构造函数的参数,否则通常不会编译。一个例子是当它KEY是一个整数。传递构造函数方法引用实际上会调用new ArrayList(KEY)...这显然不是你想要的。

为了说服你这是最好的解决方案,我使用JMH做了一些基准测试。结果如下:

Benchmark                               Mode  Cnt         Score        Error  Units
MapBenchmark.computeIfAbsent_there     thrpt   40  25134018.341 ± 687925.885  ops/s (the best!)
MapBenchmark.containsPut_there         thrpt   40  21459978.028 ± 401003.399  ops/s
MapBenchmark.getPut_there              thrpt   40  24268773.005 ± 690893.070  ops/s
MapBenchmark.putIfAbsentGet_there      thrpt   40  18230032.343 ± 238803.546  ops/s
MapBenchmark.putIfAbsent_there         thrpt   40  20579085.677 ± 527246.125  ops/s

MapBenchmark.computeIfAbsent_notThere  thrpt   40   8229212.547 ± 341295.641  ops/s (the best!)
MapBenchmark.containsPut_notThere      thrpt   40   6996790.450 ± 191176.603  ops/s
MapBenchmark.getPut_notThere           thrpt   40   8009163.041 ± 288765.384  ops/s
MapBenchmark.putIfAbsentGet_notThere   thrpt   40   6212712.165 ± 333023.068  ops/s
MapBenchmark.putIfAbsent_notThere      thrpt   40   7227880.072 ± 289581.816  ops/s