2

So a number of variations of a question exist here on stackoverflow that ask how to measure the size of an object (for example this one). And the answers point to the fact, without much elaboration, that it is not possible. Can somebody explain in length why is it not possible or why does it not make sense to measure object sizes?

Community
  • 1
  • 1
Ali Zahid
  • 1,329
  • 2
  • 17
  • 23
  • Could you give any example why would you measure Objects size? – itwasntme Aug 13 '15 at 15:08
  • 1
    I'd say the answers on that question elaborate quite a bit. What exactly don't you understand about it? Objects in many managed languages have additional overhead, which includes structures use for locking/gc/etc. They also may have padding to allow for aligned member access, and what and how much padding may vary based on architecture. – Dark Falcon Aug 13 '15 at 15:09
  • @DarkFalcon so two objects of the same class would have the same overheads? or are these random? is there a way to find out how many of such overheads exist and maybe even find out their sizes individually? – Ali Zahid Aug 13 '15 at 16:29
  • @mastah say to find out which class on average takes up more memory than the other – Ali Zahid Aug 13 '15 at 16:30

3 Answers3

2

I guess from the tags that you are asking about measurements of object sizes in Java and C#. Don't know much about C# therefore the following only pertains to Java.

Also there is a difference between the shallow and detained size of a single object and I suppose you are asking about the shallow size (which would be the base to derive the detained size).

I also interpret your term managed environment that you only want to know the size of an object at runtime in a specific JVM (not for instance calculating the size looking only at source code).

My short answers first:

  • Does it make sense to measure object sizes? Yes it does. Any developer of an application which runs under memory constraints is happy to know the memory implications of class layouts and object allocations.
  • Is it impossible to measure in managed environments? No it is not. The JVM must know about the size of its objects and therefore must be able to report the size of an object. If we only had a way to ask for it.

Long answer:

There are plenty of reasons why the object size cannot be derived from the class definition alone, for example:

  • The Java language spec only gives lowerbound memory requirements for primitive types. A int consumes at least 4 bytes, but the real size is up to the VM.

  • Not sure what the language spec tells about the size of references. Is there any constraint on the number of possible objects in a JVM (which would have implications for the size of internal storage for object references)? Today's JVMs use 4 bytes for a reference pointer.

  • JVMs may (and do) pad the object bytes to align at some boundary which may extend the object size. Todays JVMs usually align object memory at a 8 byte boundary.

But all these reasons do not apply to a JVM runtime which uses actual memory layouts, eventually allows its generational garbage collector to push objects around, and must therefore be able to report object sizes.

So how do we know about object sizes at runtime? In Java 1.5 we got java.lang.instrument.Instrumentation#getObjectSize(Object). The Javadoc says:

Returns an implementation-specific approximation of the amount of storage consumed by the specified object. The result may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM.

Reading with a grain of salt this tells me that there is a reasonable way to get the exact shallow size of an object during one point at runtime.

wero
  • 32,544
  • 3
  • 59
  • 84
1
  • Getting size of object is easily possible.

  • Getting object size may have little overhead if the object is large and we use IO streams to get the size.

  • If you have to get size of larger objects very frequently, you have to be careful.

Have a look at below code.

 import java.io.*;  

    class ObjectData implements Serializable{
        private int id=1;;
        private String name="sunrise76";
        private String city = "Newyork";
        private int dimensitons[] = {20,45,789}; 
    }

    public class ObjectSize{
        public static void main(String args[]){
            try{
            ObjectData data = new ObjectData();
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(b);
            oos.writeObject(data);
            System.out.println("Size:"+b.toByteArray().length);
            }catch(Exception err){
                err.printStackTrace();
            }
        }
    }
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • 1
    The serialized bytes of an object are not a snapshot of the objects memory within the JVM, and therefore do not allow to calculate its memory size. For instance the serialized version of an object will contain its class name (as serialized string), whereas the JVM object only has pointer to a its class object. Still like your approach. – wero Aug 13 '15 at 19:49
  • The only problem with instrumentation api : It does not include size of other objects, which are part of this object. It's not deep size of the object. – Ravindra babu Aug 14 '15 at 02:13
  • @sunrise76 Thanks for your help! much appreciated! – Ali Zahid Aug 14 '15 at 02:53
0

Getting the memory size of managed types is not a straightforward task in C#. I faced a similar problem and would like to share my solution to this issue.

One approach is to use the JSON serializer to convert the object to a byte array and estimate its size. However, this method is not effective for large objects exceeding 1 GB in size.

An alternative solution is using the ManagedObjectSize NuGet package, which accesses the memory layout and properties of managed objects to calculate their size accurately. While this package can be useful for optimizing memory usage and performance, it can also be a time-consuming process, so it should be used carefully.

Amin
  • 31
  • 3