I know that Java’s implementation does everything it can to hide that information from developers, but I’m building a memory-bound algorithm which does not depend on third-party libraries, so that information would come in handy.
In particular, I am allocating many large int[] arrays as instance variables. I will investigate more compact representation soon, but right now I’m interested in knowing how much space is used to a plain array.
Well, an
intfield could end up taking up more than 4 bytes due to padding… but fundamentally it’s 4 bytes (32 bits). As for whether it does take more than 4 bytes, you’d have to experiment to find out. That’s reasonably easy to do for fields within an object; harder for stack-basedintvalues.For example, a large array of
intwill always take up roughly 4 times its length (+ a small amount of overhead for the length etc). I don’t believe padding will be applied between elements – although it would be relatively easy to verify that. The value returned byRuntime.totalMemory() - Runtime.freeMemory()should only be used carefully, but if you allocate an array of 1 million ints in one run, then 2 million ints in another, then 3 million ints next etc it should be reasonably clear what’s going on.Sample code:
On my machine, trying this with 100000, 2000000 and 3000000 gives “4*size + 16” bytes for all runs.