Peter is a DZone MVB and is not an employee of DZone and has posted 157 posts at DZone. You can read more from them at their website. View Full User Profile

Low GC in Java: Using primitives

07.10.2011
| 5886 views |
  • submit to reddit

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);
    else
        counters.put(times, count + 1);
}
Directory of performance examples

 

From http://vanillajava.blogspot.com/2011/07/low-gc-in-java-using-primitives.html

Published at DZone with permission of Peter Lawrey, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Sakdsitt Likhit... replied on Mon, 2011/07/11 - 4:41am

Peter, How you get memrory used?

Sirikant Noori replied on Sun, 2012/01/15 - 11:07am

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?

Peter Lawrey replied on Mon, 2012/01/30 - 11:35am in response to: Sakdsitt Likhitmetagul

You can use Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() and turn off -XX:-UseTLAB and you can get how much memory was used in constructing the objects (which can be more than the amount retained)

 To find out the amount retained you need to use System.gc() as well. This can trigger a Full GC on Oracle/Sun JVM, but not all JVMs will do so.

Peter Lawrey replied on Mon, 2012/01/30 - 11:36am in response to: Sirikant Noori

I implements a simple hash map of my own.  You can use TIntIntHashMap or similar.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.