I see a huge performance benefit when using putAll instead of put.
See the sample program below:
public class SampleTest {
public static void main(final String[] args) {
final Map<String, String> testMap = new HashMap<>();
final Map<String, String> 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("<<<<<<<<<Time for put>>>>>>>>>>>");
System.out.println(ChronoUnit.MILLIS.between(startTestTime, endTestTime));
final LocalDateTime startTestTime1 = LocalDateTime.now();
testMap2.putAll(testMap);
final LocalDateTime endTestTime1 = LocalDateTime.now();
System.out.println("<<<<<<<<<Time for put all>>>>>>>>>>>");
System.out.println(ChronoUnit.MILLIS.between(startTestTime1, endTestTime1));
}
}
This returns (in Milliseconds):
<<<<<<<<<Time for put>>>>>>>>>>>
1934
<<<<<<<<<Time for put all>>>>>>>>>>>
116
Conclusion:
putAll() is definitely more performant than put() with the below disclaimers.
1. This result is on my machine (i.e depends on the machine configuration). But you still see a wide difference.
2. As metioned above Map is an interface, so the performance will depend on the implementation, i have considered HashMap as it is widely used.
So if performance is a constraint you can prefer putAll() for HashMap atleast.