Increment array value using array[key]++

My Java code:

        if(wins.containsKey(winner)) {
            int currentCount = wins.get(winner);
            wins.remove(winner);

            wins.put(winner, currentCount + 1);
        } else {
            wins.put(winner, 1);
        }

This was my alternative to something I can do in PHP and even C#:

if(isset($something[$key])) {
    $something[$key]++;
} else {
    $something[$key] = 1;
}

This is going to be used in a high number of iterations in a for loop so I would like to consider performance. Is this whole remove() then puts() business killing the performance? What is an alternative?

Jon Skeet
people
quotationmark

Firstly, I strongly suspect that this isn't going to be a performance bottleneck. As ever, test the simplest code that works before you use more complicated code.

You could use AtomicInteger instead of Integer as the value type of your map. That would allow you to mutate the wrapped value, rather than replacing the whole entry. Then you'd have:

if(wins.containsKey(winner)) {
    wins.get(winner).incrementAndGet();
} else {
    wins.put(winner, new AtomicInteger(1));
}

If you can stick with Integer, you could still optimize your code further:

Integer previousValue = wins.get(winner);
int newValue = previousValue == null ? 1 : (int) previousValue + 1;
wins.put(winner, newValue);

Now there is exactly one get and one put operation on each iteration.

people

See more on this question at Stackoverflow