This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
How do you find out how much memory an object takes up in memory? I need metrics for calculating how much working memory I will need for a particular task. Even if these sizes are implementation dependant, that will still be useful as a rule-of-thumb measurement. For example, how many bytes does an Integer take up? How about a Double? How about any arbitrary object whose members I can recursively ask how big they are? Thanks
I believe the built in types (int, double, etc), are supposed to be the same on all platforms. I'm sure there's a chart somewhere. Thinking In Java Bruce Eckel's online book should have it somewhere. Don't know about class objects, though, sorry.
That's kind of tricky since it is implementation dependent, and thus, you might get different results with different JVM providers. But I guess, what counts to you is that you get that information no matter who the provider is. I remember somebody asking that question a couple of months ago... Wait... I can't find the discussion anymore but I swear it is somewhere... In the meantime here is a piece of Java code http://www.sosnoski.com/Performance/Code/ObjectSize.java I guess you can use it to discover the size of any object.
The primitive types have standard ranges specified - from which it is possible to deduce the minimum amount of memory required. However there is no guarantee that a given implementation won't use more than the minimum memory - usually if the system's word size is larger. To find out experimentally how much space is taken by either primitives or objects on a given machine, I usually use the totalMemory() and freeMemory() methods of Runtime. The differentce between these is what we want, as it reprents used memory. Measure this quantity immediately before and after creating objects to see how much space they take. Note that these methods are approximate - they tend to be rounded off at some level. I usually get around this by creating an array with thousands of objects, and measuring its size. Be sure to measure memory usage of the empty array, as well as after it's loaded with objects. Also, it's a good idea to call System.gc() a couple times before each measurement, to minimize "noise".