Friday, March 15, 2013

When 2 is less than 1

Suppose you have a data structure with a boolean field, but the field is lazily initialized, so you need to know whether it has been initialized. Do you immediately think of using a Boolean object instead of a boolean primitive so that you can use the null reference to represent not initialized? What about using a second boolean instead to represent initialization state?

Which way is better? Let’s analyze this question from memory usage standpoint. A boolean primitive takes up one byte. The object header for an empty object on a 64-bit JVM is twelve bytes. Of course, a Boolean object is not empty, it has a boolean primitive inside of it, so that’s thirteen bytes. So we are looking at thirteen bytes for the one field solution vs. two bytes for the two field solution.

Does this matter in all situations? Of course, not. But if there will be many instances of your data structure, the memory savings add up very quickly.