We all know that Java is a memory hog. This page aims to give you an idea how much it actually hogs without using a profiler.
A reference to an object is in this listing also considered to be a primitive type.
- boolean: 1 byte
- byte: 1 byte
- char: 2 bytes
- short: 2 bytes
- int: 4 bytes
- long: 8 bytes
- float: 4 bytes
- double: 8 bytes
- reference: 4 bytes
Each Java object uses the following:
- 8 byte Object overhead
- size of all primitives and references combined
- The total size must be a multiple of 8, so add bytes till you have a multiple of 8.
- 12 byte overhead
- size of the array times the size of the primitive type
- Integer = 8 overhead + 4 data + 4 padding = 16 bytes
- String = 8 bytes overhead + 2 * the number of characters in the char + 12 bytes overhead for the char array + 8 bytes for two int fields = 32 bytes for an empty String + 2 bytes for each character.
Using auto-boxed primitives or Strings as keys in a large Map will give you very large amounts of overhead.