Home > Java > javaTutorial > How to Measure the Size of Objects in Java?

How to Measure the Size of Objects in Java?

Susan Sarandon
Release: 2024-11-17 10:16:03
Original
185 people have browsed it

How to Measure the Size of Objects in Java?

Measuring Object Size in Java

In Java, determining the memory consumption of an object is not as straightforward as in languages like C/C where the sizeof() function can be utilized. However, an alternative approach exists using the java.lang.instrumentation package.

This package provides a versatile method for obtaining an implementation-specific approximation of an object's size, including any associated overhead:

<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 use this functionality, simply call getObjectSize() like so:

<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

This approach offers a robust way to estimate the memory consumption of Java objects, enabling developers to analyze and optimize data structures effectively.

The above is the detailed content of How to Measure 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