Friday, 8 August 2014

Java ArrayList and HashMap Performance Improvement in JDK 1.7| Empty List and Map will Cost Less Memory

From long time one reason for me to update to newer Java version was always bug fix and performance improvement. Apart from major changes like Generics in Java 1.5 and Lambdas in Java 8, there are so many small improvements, performance optimization which just goes under radar, one of such change is creating empty ArrayList and HashMap with size zero in JDK 1.7.0_40 update. Many Java developer doesn't even know about these changes, part of the blame lies on Java developers like me, as I hardly read release notes of minor Java updates. Some times these changes are done as part of bug fixes and other time as minor optimization, but given popularity of ArrayList and HashMap in Java application impact of this simple Java optimization is huge. If you are running on Java 1.6 or earlier version of Java 1.7, you can open code of java.util.ArrayList and check that, currently empty ArrayList is initialized with Object array of size 10. If you create several temporary list in your program, which remains uninitialized, due to any reason then you are not only losing memory but also losing performance by giving your garbage collector more work. Same is true for empty HashMap, which was initialized by default initial capacity of 16. This changes are result of observation made by Nathan Reynolds, and Architect at Oracle, which apparently analysed 670 Java heap dumps from different Java programs to find out memory hogs.

No comments:

Post a Comment