Search code examples
javaheap-dumpeclipse-memory-analyzer

Why is the size of a Java object different more than two bytes when I replace an int with a short?


I am developing a Red Black Tree and using Eclipse Memory Analyzer Tool to measure the space that its nodes occupy.

I noticed that when I replace the int variable I use to keep the height of the tree with a short variable, the retained heap of each node drops from 40 to 32.

public class RedBlackBST {
  private static final boolean RED   = true;
  private static final boolean BLACK = false;

  private Node root;

public class Node {
  public int key;
  public Node left, right;
  private boolean color;
  private int N;
}

You can see this effect in the following figures:

With an int for N (used for the height) the shallow and retained heaps for a random node of the tree is 40.

int1 int2

With a short for N the shallow and retained heaps for a random node of the tree is 32.

short1 short2

I thought that the difference should be just two bytes. Why is it 8?

I would also very much appreciate an explanation for the two figures regarding the rest of the variables. I am puzzled that both size heaps are dividers of 2, as I would expect that the boolean variable color would be of size 1. Keep in mind that the first ref in the attributes tab is to the RedBlackBST instance.


Solution

  • Difference is caused by the reason that JVM which You are using is aligning the object sizes to 8. So You are probably using Oracle's Hotspot at 64bit architecture. It's done so bevause of performance reasons.