I will try to explain the numbers mentioned in the original article.
The article describes object metadata, usually consisting of: class, flags, and locks.
The class and lock are stored in the object header and occupy 8 bytes on a 32-bit virtual machine. I did not find any information about the JVM implementation that has flag information in the object header. Perhaps this is stored somewhere outside (for example, by a garbage collector to count references to an object, etc.).
So, let's say that the article talks about some x32 AbstractJVM, which uses 12 bytes of memory to store meta-information about the object.
Then for char[] we have:
- 12 bytes of meta information (8 bytes on x32 JDK 6, 16 bytes on x64 JDK)
- 4 bytes for array size
- 2 bytes for each character stored
- 2 alignment bytes if the number of characters is odd (on x64 JDK:
2 * (4 - (length + 2) % 4) )
For java.lang.String we have:
- 12 bytes of meta information (8 bytes on x32 JDK6, 16 bytes on x64 JDK6)
- 16 bytes for string fields (this is for JDK6, 8 bytes for JDK7)
- memory needed to store char [] as described above
So, let it count how much memory it takes to store "MyString" as a String object:
12 + 16 + (12 + 4 + 2 * "MyString".length + 2 * ("MyString".length % 2)) = 60 bytes.
On the other hand, we know that to store only data (without information about the data type, length or something else) we need:
2 * "MyString".length = 16 bytes
Overhead 60/16 60 / 16 = 3.75
Similarly, for a single character array, we get the "maximum overhead":
12 + 16 + (12 + 4 + 2 * "a".length + 2 * ("a".length % 2)) = 48 bytes 2 * "a".length = 2 bytes 48 / 2 = 24
In accordance with the logic of the authors of the article, ultimately, the maximum overhead cost of infinity of value is achieved when we store an empty string :).
Andrey Nov 29 '13 at 11:00 2013-11-29 11:00
source share