Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.2k points)
I want to record how much memory (in bytes, hopefully) an object takes up for a project (I'm comparing sizes of data structures) and it seems like there is no method to do this in Java. Supposedly, C/C++ has sizeOf() method, but this is nonexistant in Java. I tried recording the free memory in the JVM with Runtime.getRuntime().freeMemory() before and after creating the object and then recording the difference, but it would only give 0 or 131304, and nothing in between, regardless of the number of elements in the structure. Help please!

1 Answer

0 votes
by (46k points)

You can use the java.lang.instrumentation package:

http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html

It has a method that can be used to get the implementation specific approximation of object size, as well as overhead associated with the object.

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);

    }

}

Use getObjectSize:

public class C {

    private int x;

    private int y;

    public static void main(String [] args) {

        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));

    }

}

Source:

In Java, what is the best way to determine the size of an object?

Related questions

0 votes
1 answer
asked Aug 29, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...