当使用putAll而不是put时,我看到巨大的性能优势。 请参见下面的示例程序:
公共类SampleTest {
public static void main(final String[] args) {
final Map testMap = new HashMap<>();
final Map testMap2 = new HashMap<>();
final LocalDateTime startTestTime = LocalDateTime.now();
for(int i=0; i < 1000000; i++) {
testMap.put(i+"", i+"");
}
final LocalDateTime endTestTime = LocalDateTime.now();
System.out.println("<<<<<<<<>>>>>>>>>>");
System.out.println(ChronoUnit.MILLIS.between(startTestTime, endTestTime));
final LocalDateTime startTestTime1 = LocalDateTime.now();
testMap2.putAll(testMap);
final LocalDateTime endTestTime1 = LocalDateTime.now();
System.out.println("<<<<<<<<>>>>>>>>>>");
System.out.println(ChronoUnit.MILLIS.between(startTestTime1, endTestTime1));
}
}
这返回(毫秒):
<<<<<<<<>>>>>>>>>>
1934
<<<<<<<<>>>>>>>>>>
116
结论: 的putAll()肯定更比使用下面的免责声明更高效。 1.此结果在我的机器上(即取决于机器配置)。但你仍然看到很大的差异。 2.如上所述Map是一个接口,所以性能取决于实现,我已经考虑到了HashMap的广泛使用。 所以如果性能是一个约束,你可以更喜欢putAll()为HashMap atleast。