简体   繁体   中英

How can I determine how much memory my classes use?

I had a discussion with my Computer Science teacher about how much memory a class in JAVA takes up. Neither of us knew a specific answer, but I had a few questions that he couldn't answer.

1) Is it as simple as each classes' amount of bytes that its primitive data types use is what determines its memory usage?

2) If you make an instance of a class and set it to null, would it still take up as many bytes as an instance that is not null?

3) Does a String with 100 characters in it, have the same amount of bytes as a single character string?

4) If a class has no variables, no methods, nothing, and just looks like this:

public class Test{}

would it still take up memory?

You're confusing between two different things: the amount of memory that a class takes (meta-data, or "the blueprint" of the instances) and the amount of memory that an instance takes (data/object).

For classes you can use java.lang.instrument.Instrument.getObjectSize(yourObject.getClass()); and as for an instance - it doesn't necessarily has a fixed size. For example, if you have an instance of Person and it has a name field - then different names will capture different space according to the length of the String.

You can use profilers in order to see how much memory instances take, YourKit is an excellent profiler but it's not free.

Use this: java.lang.instrument package

Compile that library and include in your jar. Then:

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

In Manifest.MF add:

Premain-Class: ObjectSizeFetcher

Now do:

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new Test()));
    }
}

You can invoke your code with:

java -javaagent:ObjectSizeFetcherAgent.jar C

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

You can measure the size using the technique here:

https://stackoverflow.com/a/383597/3049628

Beyond that you can usually guess the rough amount of memory (most things are either 4 bytes or 8 depending on in a 32 bit or 64 bit systems. Arrays are packed better.) but the actual implementation is JVM dependent so there is no fixed rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM