Java memory usage

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.
Primitive types
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

Objects
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.
  • Arrays

    • 12 byte overhead
    • size of the array times the size of the primitive type

    Some examples

    • 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.

Comments

As tested today, Seems like

As tested today, Seems like JVM-64bit, The Reference take 8bytes. And Arrays take 24 bytes overhead.

Br,
Suttiwat