Tip of the day: dealing with Boxed Numbers

Boxed numbers are objects such as java.lang.Integer, java.lang.Float etc. Each such object is allocated on the heap, contains all the standard internal “bookkeeping” data that the JVM needs, and therefore takes much more memory than its “payload” value. For example, a plain int number takes 4 bytes, but an instance of java.lang.Integer takes 16 bytes in most JVM implementations.

Boxed numbers were introduced mainly to support “numeric” elements in collections such as ArrayLists or HashMaps. That works, and in many cases doesn’t cause any issues. However, if at run time your app creates millions of collections such as HashMap<String, Float>, the instances of Float may well take gigabytes of memory, and furthermore may contribute to long GC pauses. The latter is due to the fact that GC time is proportional to both size and number of objects in the heap, and boxed objects, though each of them is small, may easily become very numerous.

For these reasons, JXRay treats boxed numbers as “pure evil” and highlights them in its reports whenever they use any noticeable amount of memory. The overhead in bytes that JXRay gives for them is the amount of memory that you will save if you replace each boxed object with the corresponding plain number.

Fortunately, it’s generally easy to get rid of boxed numbers. If you see a data field declaration like Float x; , usually it can be simply replaced with float x; . A boxed type here is either a mistake or is used to signal an uninitialized (null) state of x. But the latter can be achieved by e.g. using some special value, such as Float.MIN_VALUE, instead of null.

What about the original purpose of boxed types, i.e. support of collections with numbers? Fortunately, these days good alternatives – libraries of specialized collections – are available. Our favorite one is fastutil. This library provides collections such as Object2IntOpenHashMap, that uses a lot less memory than the standard HashMap<Object, Integer>, and may also be faster.

If you would like to learn more, read this detailed article. We hope that from now on, you will use boxed numbers judiciously!

Leave a Reply

Your email address will not be published. Required fields are marked *