1. 程式人生 > >如何計算java中的物件object大小size

如何計算java中的物件object大小size

 

Measuring Object Size

While the Java platform doesn't provide a way to measure the size of an object, it is possible to measure the approximate size indirectly. Section 5.1.1 discusses the Runtime methods that provide information about the size of the JVM's object heap.

You can also use these methods to determine the approximate size of an object by:

Requesting garbage collection to get the heap into a known state. Measuring the free heap space. Creating an instance of the class you want to measure and keeping a reference to it. Requesting garbage collection again. Measuring the free heap space. Subtracting the second measurement from the first.

Although this general approach works, it has some flaws:

Garbage collection can be unpredictable. Caching performed by the class when the first instance is created can skew the results. The Runtime.freeSpace method might not be accurate down to the byte level. Fortunately, you can get around most of these by: Creating a primer instance of the class before your measure the heap the first time. This eliminates the impact of one-time cache costs. Measuring several instances of the object and calculating the average. This helps offset the unpredictability inherent in the GC behavior and the heap space measurement methods. zz from oracle