博客主机
A-A+

检测Java对象所占内存大小

2009年01月03日 柴房 暂无评论

Don't pay the price for hidden class fields
By Vladimir Roubtsov, JavaWorld.com, 08/16/02

Recently, I helped design a Java server application that resembled an in-memory database. That is, we biased the design toward caching tons of data in memory to provide super-fast query performance.

Once we got the prototype running, we naturally decided to profile the data memory footprint after it had been parsed and loaded from disk. The unsatisfactory initial results, however, prompted me to search for explanations.

Since Java purposefully hides many aspects of memory management, discovering how much memory your objects consume takes some work. You could use the Runtime.freeMemory() method to measure heap size differences before and after several objects have been allocated. Several articles, such as Ramchander Varadarajan's "Question of the Week No. 107" (Sun Microsystems, September 2000) and Tony Sintes's "Memory Matters" (JavaWorld, December 2001), detail that idea. Unfortunately, the former article's solution fails because the implementation employs a wrong Runtime method, while the latter article's solution has its own imperfections:

    A single call to Runtime.freeMemory() proves insufficient because a JVM may decide to increase its current heap size at any time (especially when it runs garbage collection). Unless the total heap size is already at the -Xmx maximum size, we should use Runtime.totalMemory()-Runtime.freeMemory() as the used heap size.

    Executing a single Runtime.gc() call may not prove sufficiently aggressive for requesting garbage collection. We could, for example, request object finalizers to run as well. And since Runtime.gc() is not documented to block until collection completes, it is a good idea to wait until the perceived heap size stabilizes.

    If the profiled class creates any static data as part of its per-class class initialization (including static class and field initializers), the heap memory used for the first class instance may include that data. We should ignore heap space consumed by the first class instance.

Considering those problems, I present Sizeof, a tool with which I snoop at various Java core and application classes:

  1. public class Sizeof
  2. {
  3. public static void main (String [] args) throws Exception
  4. {
  5. // Warm up all classes/methods we will use
  6. runGC ();
  7. usedMemory ();
  8. // Array to keep strong references to allocated objects
  9. final int count = 100000;
  10. Object [] objects = new Object [count];
  11. long heap1 = 0;
  12. // Allocate count+1 objects, discard the first one
  13. for (int i = -1; i <>
  14. {
  15. Object object = null;
  16. // Instantiate your data here and assign it to object
  17. object = new Object ();
  18. //object = new Integer (i);
  19. //object = new Long (i);
  20. //object = new String ();
  21. //object = new byte [128][1]
  22. if (i >= 0)
  23. objects [i] = object;
  24. else
  25. {
  26. object = null; // Discard the warm up object
  27. runGC ();
  28. heap1 = usedMemory (); // Take a before heap snapshot
  29. }
  30. }
  31. runGC ();
  32. long heap2 = usedMemory (); // Take an after heap snapshot:
  33. final int size = Math.round (((float)(heap2 - heap1))/count);
  34. System.out.println ("'before' heap: " + heap1 +
  35. ", 'after' heap: " + heap2);
  36. System.out.println ("heap delta: " + (heap2 - heap1) +
  37. ", {" + objects [0].getClass () + "} size = " + size + " bytes");
  38. for (int i = 0; i <>null;
  39. objects = null;
  40. }
  41. private static void runGC () throws Exception
  42. {
  43. // It helps to call Runtime.gc()
  44. // using several method calls:
  45. for (int r = 0; r < 4; ++ r) _runGC ();
  46. }
  47. private static void _runGC () throws Exception
  48. {
  49. long usedMem1 = usedMemory (), usedMem2 = Long.MAX_VALUE;
  50. for (int i = 0; (usedMem1 <>500); ++ i)
  51. {
  52. s_runtime.runFinalization ();
  53. s_runtime.gc ();
  54. Thread.currentThread ().yield ();
  55. usedMem2 = usedMem1;
  56. usedMem1 = usedMemory ();
  57. }
  58. }
  59. private static long usedMemory ()
  60. {
  61. return s_runtime.totalMemory () - s_runtime.freeMemory ();
  62. }
  63. private static final Runtime s_runtime = Runtime.getRuntime ();
  64. } // End of class

Sizeof's key methods are runGC() and usedMemory(). I use a runGC() wrapper method to call _runGC() several times because it appears to make the method more aggressive. (I am not sure why, but it's possible creating and destroying a method call-stack frame causes a change in the reachability root set and prompts the garbage collector to work harder. Moreover, consuming a large fraction of the heap space to create enough work for the garbage collector to kick in also helps. In general, it is hard to ensure everything is collected. The exact details depend on the JVM and garbage collection algorithm.)

Note carefully the places where I invoke runGC(). You can edit the code between the heap1 and heap2 declarations to instantiate anything of interest.

Also note how Sizeof prints the object size: the transitive closure of data required by all count class instances, divided by count. For most classes, the result will be memory consumed by a single class instance, including all of its owned fields. That memory footprint value differs from data provided by many commercial profilers that report shallow memory footprints (for example, if an object has an int[] field, its memory consumption will appear separately).
The results

Let's apply this simple tool to a few classes, then see if the results match our expectations.

Note: The following results are based on Sun's JDK 1.3.1 for Windows. Due to what is and is not guaranteed by the Java language and JVM specifications, you cannot apply these specific results to other platforms or other Java implementations.
java.lang.Object

Well, the root of all objects just had to be my first case. For java.lang.Object, I get:

So, a plain Object takes 8 bytes; of course, no one should expect the size to be 0, as every instance must carry around fields that support base operations like equals(), hashCode(), wait()/notify(), and so on.
java.lang.Integer

My colleagues and I frequently wrap native ints into Integer instances so we can store them in Java collections. How much does it cost us in memory?

The 16-byte result is a little worse than I expected because an int value can fit into just 4 extra bytes. Using an Integer costs me a 300 percent memory overhead compared to when I can store the value as a primitive type.
java.lang.Long

Long should take more memory than Integer, but it does not:

Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a Long is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, Integer had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.
Arrays

Playing with primitive type arrays proves instructive, partly to discover any hidden overhead and partly to justify another popular trick: wrapping primitive values in a size-1 array to use them as objects. By modifying Sizeof.main() to have a loop that increments the created array length on every iteration, I get for int arrays:

Java代码
  1. length: 0, {class [I} size = 16 bytes
  2. length: 1, {class [I} size = 16 bytes
  3. length: 2, {class [I} size = 24 bytes
  4. length: 3, {class [I} size = 24 bytes
  5. length: 4, {class [I} size = 32 bytes
  6. length: 5, {class [I} size = 32 bytes
  7. length: 6, {class [I} size = 40 bytes
  8. length: 7, {class [I} size = 40 bytes
  9. length: 8, {class [I} size = 48 bytes
  10. length: 9, {class [I} size = 48 bytes
  11. length: 10, {class [I} size = 56 bytes

and for char arrays:

Java代码
  1. length: 0, {class [C} size = 16 bytes
  2. length: 1, {class [C} size = 16 bytes
  3. length: 2, {class [C} size = 16 bytes
  4. length: 3, {class [C} size = 24 bytes
  5. length: 4, {class [C} size = 24 bytes
  6. length: 5, {class [C} size = 24 bytes
  7. length: 6, {class [C} size = 24 bytes
  8. length: 7, {class [C} size = 32 bytes
  9. length: 8, {class [C} size = 32 bytes
  10. length: 9, {class [C} size = 32 bytes
  11. length: 10, {class [C} size = 32 bytes

Above, the evidence of 8-byte alignment pops up again. Also, in addition to the inevitable Object 8-byte overhead, a primitive array adds another 8 bytes (out of which at least 4 bytes support the length field). And using int[1] appears to not offer any memory advantages over an Integer instance, except maybe as a mutable version of the same data.
Multidimensional arrays

Multidimensional arrays offer another surprise. Developers commonly employ constructs like int[dim1][dim2] in numerical and scientific computing. In an int[dim1][dim2] array instance, every nested int[dim2] array is an Object in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ. For example, a int[128][2] instance takes 3,600 bytes. Compared to the 1,040 bytes an int[256] instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of byte[256][1], the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.
java.lang.String

Let's try an empty String, first constructed as new String():

Java代码
  1. 'before' heap: 510696, 'after' heap: 4510696
  2. heap delta: 4000000, {class java.lang.String} size = 40 bytes

The result proves quite depressing. An empty String takes 40 bytes—enough memory to fit 20 Java characters.

Before I try Strings with content, I need a helper method to create Strings guaranteed not to get interned. Merely using literals as in:

Java代码
  1. object = "string with 20 chars";

will not work because all such object handles will end up pointing to the same String instance. The language specification dictates such behavior (see also the java.lang.String.intern() method). Therefore, to continue our memory snooping, try:

Java代码
  1. public static String createString (final int length)
  2. {
  3. char [] result = new char [length];
  4. for (int i = 0; i <>char) i;
  5. return new String (result);
  6. }
标签:

给我留言

Copyright © 小小的数据技术梦想 保留所有权利.   Theme  Ality 浙ICP备12043346号-1

用户登录

分享到: