How much memory does Java – hashtable use?

In Java, if I create a hashtable < K, V > and put n elements in it, how much memory does it take? If it depends on implementation, what is a good "guess"?

Solution

Editing; Oh, Geez, I'm an idiot. I gave HashMap information instead of hashtable However, after checking, these implementations are the same for storage purposes

This depends on your VM's internal memory settings (item packaging, 32 - or 64 - bit pointer and word alignment / size) and is not specified by Java

Basic information on estimating memory usage can be found here

You can estimate it like this:

>A pointer is 4 bytes on a 32-bit virtual machine and 8 bytes on a 64 bit virtual machine. > The object overhead is 8 bytes of memory (nothing for empty objects) > the size of the object filled to a multiple of 8 bytes (ugh). > Each HashMap has a small, constant overhead: one float, three ints, plus object overhead. > There is a set of slots, some of which will have entries, some of which will remain new The ratio of filled slots to total slots does not exceed the specified load factor in the constructor. > The slot array requires an object overhead, plus an int size, plus a pointer to each slot to indicate the stored object. > The number of slots is usually 1.3 to 2 times the number of storage mappings. The default load factor is 0.75, but it may be less than this value, depending on Hash conflicts. > Each stored mapping requires an entry object This requires an object overhead, three pointers, plus stored key and value objects, plus an integer

So put it together (for a 32 / 64 bit sun hotspot JVM): HashMap requires 24 bytes (itself, original field) 12 bytes (slot array constant) 4 or 8 bytes per slot 24 / 40 bytes per entry key object size value object size fills each object to more than 8 bytes

Or roughly (at most, the default setting cannot be guaranteed to be accurate):

>32-bit JVM: 36 bytes 32 bytes / mapping key & value > 64 bit JVM: 36 bytes 56 bytes / mapping key & value

Note: This requires more checking. The object overhead on 64 bit VM may require 12 bytes I don't know null values - null pointers may be compressed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>