Finding myself in a situation of needing to increment values in a map in Java, I was curious to see what the most efficient way to do so. Said piece of code will be looped over thousands of times and I wanted it to run as quickly possible. Yes, I know that pre-optimization is the root of all evil, but in this case it was something I needed to be conscious of.
I found a question/thread on StackOverflow where someone else had already pondered the same thing and got a long list of possible answers to compare to each other, including using Apache Commons and the Google Collections Library. After testing all of them, the fastest way ended-up being implementing a "MutableInt" class and using it as the value data type in the map:
-
class MutableInt {
-
int value = 0;
-
public void inc () { ++value; }
-
public int get () { return value; }
-
}
-
-
Map<string ,MutableInt> map = new HashMap<string ,MutableInt>();
-
MutableInt value = map.get (key);
-
if (value == null) {
-
value = new MutableInt ();
-
map.put (key, value);
-
} else {
-
value.inc ();
-
}
Pretty interesting stuff! Note that the above code snippet is not very cleanly formatted, but you'll get the idea.
3 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
Have you looked at java.util.concurrent.atomic.AtomicInteger? It's part of Java 5 and up I believe. It has methods for both incrementing and retrieving values much the way the MutableInt class you've created does.
Matthew,
I haven't looked at that before, but good find.. seems like there were a lot of minor enhancements in Java 5 that I forget about.
It may be fast, but it's not thread-safe. You're aware of this, right?