Low GC in Java: Using primitives


In a recent article I examined how using primitives and collections which support primitives natively instead of Wrappers and standard collections can reduce memory usage and improve performance.

Different way to have a Map of int/Integer

There are a number of ways you can use int/Integer and a number of collections you store them in. Depending on which approach you use can have a big difference on the performance and the amount of garbage produced.
TestPerformance RangeMemory used
Use Integer wrappers and HashMap71 - 134 (ns) 53 MB/sec
Use int primitives and HashMap45 - 76 (ns)36 MB/sec
Use int primitives and FastMap58 - 93 (ns)28 MB/sec
Use int primitives and TIntIntHashMap18 - 28 (ns) nonimal
Use int primitives and simple hash map6 - 9 (ns) nonimal
The performance range was the typical (50%tile) and one of the higher (98%tile) timings. The garbage was the result of 900,000 loops per second.

These tests were run on my new system.

The Code

Loop tested
int runs = 300 * 300;
for (int i = 0; i < runs; i++) {
    int x = i % 300;
    int y = i / 300;
    int times = x * y;
    Integer count = counters.get(times);
    if (count == null)
        counters.put(times, 1);
        counters.put(times, count + 1);

Link to all the code is here

Directory of performance examples


  1. Hi!
    I found your article very interesting.
    What do you mean by "Use int primitives and simple hash map", did you implemented your own Hash Map functions?

  2. @akoskm, Yes, the simple HashMap implements just what is required for the test. Its code in in the "Directory of performance examples" link, or you can click SimpleHashMap


Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues