I am currently designing a data structure in which I’m trying to keep memory consumption to a minimum. I have a few instance variables that may be null depending on the placement of the Node in the Trie. I started going down the path of creating separate classes (one that has the instance variable and one that doesn’t) so that I won’t waste tons of space with null references… but then I started to wonder how the jvm works. Does it still eat up the full 8 bytes (assuming x64 arch) if the object reference is null or does it have a more optimal way to store a null reference?
Share
I’m almost sure JVMs will use as much space for a
nullreference as for any other one. If you have an object with say 3 reference fields, and you null out the one in the middle, I don’t think any virtual machine would be able to move the 3rd one and save the 4 or 8 bytes (and then when you changed thenullto something else, it would have to move stuff around again). If if this was technically feasible, it would not be worth it – the extra computational cost and code complexity would kill any potential gains. Also, partly due to C heritage, on most machines a pointer equal bit-wise to 0 works as a NULL at a very low level, so thenullreference has a rather obvious representation.On Oracle/Sun JDK you can use -XX:+UseCompressedOops command line argument to make references 4 bytes instead of 8 on 64-bit if your heap is smaller than 16 GB (regardless of whether the reference is
nullor not).