6

How can we find out the size of a Java object?

Example:

class Person{
    String name;  
    int age;  

    public Person(String n, int a){  
        name = n;  
        age = a;  
    }
}  

Person person = new Person("Andy", 30);  

How can I know the size of person object?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • 3
    Why do you need to know the size of the object? – Oliver Charlesworth Nov 06 '10 at 21:26
  • 2
    If you really need to know... http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – robert_x44 Nov 06 '10 at 21:33
  • consider the scenario where we have limited memory and application has multiple objects taking up space, how would we then identify which object is taking more space and handle accordingly. – daydreamer Nov 06 '10 at 21:35
  • limited memory could be anywhere, perhaps my desktop/laptop in relation to the application I am running – daydreamer Nov 06 '10 at 22:44
  • @leaner, I can tell you this data structure is tiny for a desktop. So small you shouldn't be worrying about it. – Peter Lawrey Nov 06 '10 at 22:54
  • 1
    Does this answer your question? [In Java, what is the best way to determine the size of an object?](https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – Nolequen Oct 31 '21 at 08:44

6 Answers6

9

The question is not meaningful, at least not without further context.

The notion of "size" in Java is only reasonably well defined for primitives: A byte is 8 bit (unsurprisingly) an int is 32 bit, a long 64bit, etc. (see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for a full list).

For object instances, it's more complicated, because:

  • Object instances can (and usually will) contain references to other instances internally, so you must decide whether to count these dependent instances, and how. What if several instances share a dependency?
  • Sometimes, object instances may be reused (e.g. interning of java.lang.String, see http://en.wikipedia.org/wiki/String_interning ). So if you use x objects of size y, the total size may be smaller than x*y
  • The JVM has a lot of leeway about how to implement objects and instances internally. It may use different techniques for different instances (e.g. sharing internal data structures), so there may not even be a meaningful "size" to assign to a single object.

Maybe you could explain why you are interested in object sizes.

There are some rules of thumb for estimating the heap memory used by instances (e.g. in the Sun JVM, a java.lang.Object instance uses 8 byte), but these will depend on the JVM you use.

Generally, if you want to know about your heap usage, use a memory / heap profiler.

Edit:

Well, there is (as of JDK 6) a way to get an approximation of the amount of memory used by an object: http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29

It's still only an approximation...

sleske
  • 81,358
  • 34
  • 189
  • 227
2

I think you can get something that might help you if you do something like this:

    /* First trigger classloading */
    MyObject delegate = new MyObject();

    Runtime.getRuntime().gc();

    long before = Runtime.getRuntime().freeMemory();
    MyObject delegate2 = new MyObject();
    long after = Runtime.getRuntime().freeMemory();

    System.out.println("Memory used:"+(before-after));

This will hopefully give you the answer you want, or at least an approximation.

Knubo
  • 8,333
  • 4
  • 19
  • 25
  • What about multi-threaded situations? If two objects of the same size are allocated at the same time, then the value of memory used will be twice the size wanted. – Richard J. Ross III Nov 06 '10 at 22:01
  • I'd make a small controlled test for the objects I want to messure. If you do this in a threaded environment, then all bets are off. – Knubo Nov 06 '10 at 22:05
1

EhCache provides a SizeOf class that will try to use the Instrumentation agent and will fall back to a different approach if the agent is not loaded or cannot be loaded (details here).

Also see the agent from Heinz Kabutz.

sourcedelica
  • 23,940
  • 7
  • 66
  • 74
1

You can use the sizeof4j library to calculate the size of any object in java like SizeOf.shallowSize(new Integer(2))

Artur Mkrtchyan
  • 921
  • 9
  • 9
0

Objects. To determine the memory usage of an object, we add the amount of memory used by each instance variable to the overhead associated with each object, typically 16 bytes. The overhead includes a reference to the object’s class, garbage collection information, and synchronization information. Moreover, the memory usage is typically padded to be a multiple of 8 bytes (machine words, on a 64-bit machine). For example, an Integer object uses 24 bytes (16 bytes of overhead, 4 bytes for its int instance variable, and 4 bytes of padding)

Reference : http://www.amazon.com/Algorithms-4th-Edition-Robert-Sedgewick/dp/032157351X

daydreamer
  • 87,243
  • 191
  • 450
  • 722
-3

Java has no built in sizeof operator.

You could try and use a serialization method, by serializing an object to memory and getting the size of that data, but that wouldn't necessarily be the size you want.

You could also have a method called sizeOf(), like this:

// returns the size of this object in bytes
int sizeOf()
{
     int size = 0;
     size += name.Length * 2; // each character in name is 2 bytes, no?
     size += 4; // for n, which is 32 bits = 4 bytes
}

Note that this implementation doesn't include the metadata inside name, only the number of bytes necessary to make the char[] for it.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • But also this wouldn't show how much space headers or so take. – thejh Nov 06 '10 at 21:30
  • Edited, I added that information... honestly, I don't think that Java was ever intended to have a function like that... – Richard J. Ross III Nov 06 '10 at 21:31
  • I believe serialization is not the precise way of doing it, since it adds metadata with objects so that de-serialization process knows how to reconstructs the object – daydreamer Nov 06 '10 at 21:34
  • Correct. The second method is more accurate, but still, why would you need to know the size of an object.. is this size similar to the C/C++ `sizeof`? – Richard J. Ross III Nov 06 '10 at 21:35
  • @Richard, I have no idea, RD just gave one link above, check that out, that seems good! – daydreamer Nov 06 '10 at 21:37
  • The size of a serialized object may differ a lot from the memory used by the object instance. String are e.g. serialized using UTF-8 encoding, but in-memory, the String instances are using UTF-16 internally (at least in Oracle's VM). – jarnbjo Nov 06 '10 at 21:57
  • I said that in my answer :) yes, it isn't perfect, but java I do not think was truly intended to have such a function.. – Richard J. Ross III Nov 06 '10 at 22:00