1

Is the new map function for compute slower than using a combination of containsKey, get and put

counter.compute(tree[j], (k, v) -> {
  if (v == null) {
    v = 0;
  }

  return v + 1;
});

I tend to use containsKey, get and put in this combination

if (counter.containsKey(tree[j])) {
  counter.put(tree[j], counter.get(tree[j] + 1);
}
else {
  counter.put(tree[j], 1);
}

I feel that compute tends to work a bit slower but I don't know how to benchmark to actually understand the performance difference

chirag7jain
  • 1,485
  • 3
  • 26
  • 43
  • Check this https://stackoverflow.com/questions/8423789/benchmarking-inside-java-code – Sergei Sirik May 07 '19 at 21:48
  • I have no data to back this up but I would think that any level of indirection via a lambda or using methods is slower than what you suggest. I wrote some code which would cater to supporting both arrays and lists, using the appropriate lambdas to manipulate the values. It was immensely slower than just having two versions. – WJS May 07 '19 at 21:48
  • You may also want to check out the Java Microbenchmark Harness for doing testing. – WJS May 07 '19 at 21:54
  • 1
    Also consider: the JDK authors did the hard work so you didn't have to. Every time you need to update a value that's already in your map, using your preferred solution, you have three calls to make: containsKey, put and get. Versus a single call: compute. By default you assume the JDK is optimized already. You could also use merge to make things a little more readable using merge: `counter.merge(tree[j], 1, Integer::sum)`. Under the hood you can reason that "if the key is not present, I save myself an extra method". – Not a JD May 07 '19 at 22:43

0 Answers0