Home > Java > javaTutorial > body text

How to Determine the Size of Objects in Java?

Linda Hamilton
Release: 2024-11-04 20:15:02
Original
809 people have browsed it

How to Determine the Size of Objects in Java?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template