Finding the Size of Objects in Java
In Java, the question of determining the memory footprint of an object arises frequently when comparing data structures. However, unlike C/C with its sizeOf() method, Java lacks an explicit method for this purpose.
Solution: Utilizing java.lang.instrumentation
The lack of a built-in method in Java necessitates an alternative approach. One suitable solution is to leverage the java.lang.instrumentation package. This package provides a method that delivers an implementation-specific approximation of an object's size, along with any associated overhead.
Code Example:
The following code snippet demonstrates the usage of the java.lang.instrumentation package to retrieve object sizes:
<code class="java">import java.lang.instrument.Instrumentation; public class ObjectSizeFetcher { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } public static long getObjectSize(Object o) { return instrumentation.getObjectSize(o); } }</code>
To determine the size of an object, simply use the getObjectSize method:
<code class="java">public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); } }</code>
The above is the detailed content of How to Determine the Size of Objects in Java?. For more information, please follow other related articles on the PHP Chinese website!