How to know the size of an object in memory?

Asked

Viewed 977 times

9

I’m not after a method/operator sizeof because I already understand that JAVA doesn’t have it, but I need some way to measure at least on average how much memory an object spends, even if it is using some kind of debug.

  • 1
  • But that’s just different

  • "Possible related". So I put it like this, it’s the same theme, and as they are languages with similar functioning, this may give an idea.

  • I know, but c# has the sizeof operator, which is a crucial difference

  • I believe this function can help you getObjectSize(object), it returns the size in bytes.

  • This method belongs to which class?

  • To use getObjectSize(object) of the interface Instrumentation it is necessary to implement some steps. Put them in the answer because the way it is presented does not help and does not solve the question.

Show 2 more comments

3 answers

1

If your object is Serializable, you can use a java.io.ObjectOutputStream associated with a java.io.ByteArrayOutputStream to measure the size of your object when serialized:

class Tamanho {
    public static int tamanho(Serializable obj) {
        try (
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos)
        ) {
            oos.writeObject(obj);
            oos.flush();
            return baos.toByteArray().length;
        } catch (java.io.IOException ex) {
            // ignore a IOException que é levantada quando se fecha o oos
    }
}

Here I am using the "Try-with-Resources" construction of Java 7, which closes the streams for me. If you are using Java 6 or earlier, you can turn this construction into a try common, but as Java 7 is already very old, here is the answer...

  • And if the object has properties transient?

  • Naturally, objects pointed by properties transient will not be serialized and its size will not be computed. But if, despite that, they’re public and serialized, you can get them and serialize them explicitly, and then add up all the values you’ve achieved. It’s not simple, but we’re trying to do something that language doesn’t support.

1

You can create the sizeof method:

VMSupport.sizeOf(...)

public static int sizeOf(Object o) {
  if (VMSupport.INSTRUMENTATION != null) {
    return VMSupport.align((int) VMSupport.INSTRUMENTATION.getObjectSize(o));
  }
  return new CurrentLayouter().layout(ClassData.parseInstance(o)).instanceSize();
}

-1

If you use the eclipse, maybe this plugin will be useful to you https://www.eclipse.org/mat/ . It gives a full report and even allows you to find out if at any point in your application is occurring some memory Leak.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.