开发者

How can I calculate how much RAM an object uses?

I have a HashMap that contains 12 million entries. It m开发者_运维知识库aps String values to Long values. Each string is about ten characters long. Is it possible to calculate how much memory this map will need in RAM?


You can guess, and you can make an educated guess by looking at the size of each item that goes into the map, but your best educated guess will be wrong.

JVMs have other structure used to track references and hold type information for the classes. That will add a fixed, yet unknown amount of memory to an accurate (if you can come up with an accurate input estimate) estimate.

As only some of the memory is memory directly holding the data, and some of the memory is memory used as overhead to hold the data, you need to profile your memory consumption and based your estimates on projections of the memory "growth" when using smaller maps.

Note that profiling a JVM is a tricky task, as it is optimizing memory usage in a manner that will present varying results depending on how long the JVM is running, the activity of the Map, etc. You need to do statistical sampling of the input in a variety of conditions; but, odds are good you will eventually be able to put your finger on a reasonable number. More importantly, you will also be able to say "Well it might peak up at around this number temporarily, but should settle down to this on average". Temporal changes to memory are often overlooked in static analysis.


The JVM would know because it has to allocate and manage memory but it doesn’t tell you. So, short of going native, no, there is no way to know how much memory is actually used by your objects.


A profiler will tell you how much memory is being used by the program, and which objects are using what. You might be able to find your objects' memory usage.

VisualVM is included in Java6, and will give you this information.

It's worth mentioning, though, this is not necessarily going to give you a memory 'requirement', just a view of how much memory it is using at that point in time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜