In Java, if I create a Hashtable<K, V>
and put N elements in it, how much memory will it occupy? If it's implementation dependent, what would be a good "guess"?
Edit; Oh geez, I'm an idiot, I gave info for HashMap, not HashTable. However, after checking, the implementations are identical for memory purposes.
This is dependent on your VM's internal memory setup (packing of items, 32 bit or 64 bit pointers, and word alignment/size) and is not specified by java.
Basic info on estimating memory use can be found here.
You can estimate it like so:
So, putting it together (for 32/64 bit Sun HotSpot JVM): HashMap needs 24 bytes (itself, primtive fields) + 12 bytes (slot array constant) + 4 or 8 bytes per slot + 24/40 bytes per entry + key object size + value object size + padding each object to multiple of 8 bytes
OR, roughly (at most default settings, not guaranteed to be precise):
Note: this needs more checking, it might need 12 bytes for object overhead on 64-bit VM. I'm not sure about nulls -- pointers for nulls may be compressed somehow.
It is hard to estimate. I would read this first: http://www.codeinstructions.com/2008/12/java-objects-memory-structure.html
Just use the sunjdk tools to figure out the size of K, V and
jmap -histo [pid]
num #instances #bytes class name
1: 126170 19671768 MyKClass
2: 126170 14392544 MyVClass
3: 1 200000 MyHashtable
Also you may want to use HashMap instead of Hashtable if you do not need synchronization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With