开发者

How much memory does an int take on Sun's 64-bit JVM?

I know that Java's implementation does everything it can to hide that information from developers, but I'm building a memory-bound algorithm which does not d开发者_Go百科epend on third-party libraries, so that information would come in handy.

In particular, I am allocating many large int[] arrays as instance variables. I will investigate more compact representation soon, but right now I'm interested in knowing how much space is used to a plain array.


Well, an int field could end up taking up more than 4 bytes due to padding... but fundamentally it's 4 bytes (32 bits). As for whether it does take more than 4 bytes, you'd have to experiment to find out. That's reasonably easy to do for fields within an object; harder for stack-based int values.

For example, a large array of int will always take up roughly 4 times its length (+ a small amount of overhead for the length etc). I don't believe padding will be applied between elements - although it would be relatively easy to verify that. The value returned by Runtime.totalMemory() - Runtime.freeMemory() should only be used carefully, but if you allocate an array of 1 million ints in one run, then 2 million ints in another, then 3 million ints next etc it should be reasonably clear what's going on.

Sample code:

public class Test {
  public static void main(String[] args) {
    int size = Integer.parseInt(args[0]);

    long before = getUsedMemory();
    int[] array = new int[size];
    long after = getUsedMemory();

    long difference = after - before;
    System.out.println("Total difference: " + (after - before));
    System.out.println("Per element: " + ((double) difference) / size);
    System.out.println(array); // Make sure the array isn't GC'd early
  }

  private static long getUsedMemory() {
    Runtime rt = Runtime.getRuntime();
    return rt.totalMemory() - rt.freeMemory();
  }
}

On my machine, trying this with 100000, 2000000 and 3000000 gives "4*size + 16" bytes for all runs.


Just an int by itself? That probably depends on what it is adjacent to, etc. Or do you mean an array of int? I'm 99% sure that will take 4-bytes in all reasonable JVM implementations (plus some fixed overhead for the array object itself).

long before = Runtime.getRuntime().freeMemory();
int foo[] = new int[123456];
System.out.println("Approximate bytes per int: "
  + (before - Runtime.getRuntime().freeMemory())/(float)123456);

Reports:

Approximate bytes per int: 4.0001945


An int in Java is always 32 bits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜