Let's say we have three methods like these. They all do the same, but how different they are in terms of memory allocation and efficiency? Method one will create instances of Function during each call, but will the second method do the same? Should one always use the third version or either version is safe and the JIT compiler will take care of the memory optimization?
class Test {
Map<String, Set<String>> mapOfSets = new HashMap<>();
static final Function<String, Set<String>> FUNCTION = s -> new HashSet<>();
void method1(String key, String value) {
Function<String, Set<String>> func = s -> new HashSet<>();
mapOfSets.computeIfAbsent(key, func).add(value);
}
void method2(String key, String value) {
mapOfSets.computeIfAbsent(key, s -> new HashSet<>()).add(value);
}
void method3(String key, String value) {
mapOfSets.computeIfAbsent(key, FUNCTION).add(value);
}
}