<p>I have an application that reads a CSV file with piles of data rows.  I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause <code>OutOfMemoryError</code>s.  Each row translates into an object.  Is there an easy way to find out the size of that object programmatically?  Is there a reference that defines how large primitive types and object references are for a <code>VM</code>?</p>

<p>Right now, I have code that says read up to <strong>32,000 rows</strong>, but I'd also like to have code that says read as many rows as possible until I've used <strong>32MB</strong> of memory.  Maybe that is a different question, but I'd still like to know. </p>

[{'answer_id': 52362, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': -1, 'selected': False, 'text': '<p>I doubt you want to do it programmatically unless you just want to do it once and store it for future use.  It\'s a costly thing to do.  There\'s no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.</p>\n\n<p>One way you could do it is to serialize the thing to a File and look at the size of the file, like this:</p>\n\n<pre><code>Serializable myObject;\nObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));\noos.write (myObject);\noos.close ();\n</code></pre>\n\n<p>Of course, this assumes that each object is distinct and doesn\'t contain non-transient references to anything else.</p>\n\n<p>Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean &amp; byte = 1 byte, short &amp; char = 2 bytes, etc.), working your way down the membership hierarchy.  But that\'s tedious and expensive and ends up doing the same thing the serialization strategy would do.</p>\n'}, {'answer_id': 52377, 'author': 'sblundy', 'author_id': 4893, 'author_profile': 'https://Stackoverflow.com/users/4893', 'pm_score': 2, 'selected': False, 'text': "<p>There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.</p>\n\n<p>If that's too slow or just more trouble than it's worth, there's always good old-fashioned  row counting rule-of-thumbs.</p>\n"}, {'answer_id': 52391, 'author': 'matt b', 'author_id': 4249, 'author_profile': 'https://Stackoverflow.com/users/4249', 'pm_score': 5, 'selected': False, 'text': '<p>If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:</p>\n\n<pre><code>// Get current size of heap in bytes\nlong heapSize = Runtime.getRuntime().totalMemory();\n\n// Get maximum size of heap in bytes. The heap cannot grow beyond this size.\n// Any attempt will result in an OutOfMemoryException.\nlong heapMaxSize = Runtime.getRuntime().maxMemory();\n\n// Get amount of free memory within the heap in bytes. This size will increase\n// after garbage collection and decrease as new objects are created.\nlong heapFreeSize = Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I\'ve used 32MB of memory."</p>\n'}, {'answer_id': 52393, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 4, 'selected': False, 'text': "<p>You have to walk the objects using reflection.  Be careful as you do:</p>\n\n<ul>\n<li>Just allocating an object has some overhead in the JVM.  The amount varies by JVM so you might make this value a parameter.  At least make it a constant (8 bytes?) and apply to anything allocated.</li>\n<li>Just because <code>byte</code> is theoretically 1 byte doesn't mean it takes just one in memory.</li>\n<li>There will be loops in object references, so you'll need to keep a <code>HashMap</code> or somesuch <em>using object-equals as the comparator</em> to eliminate infinite loops.</li>\n</ul>\n\n<p>@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.</p>\n"}, {'answer_id': 52395, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 4, 'selected': False, 'text': "<p>You have to measure it with a tool, or estimate it by hand, and it depends on the JVM you are using.</p>\n\n<p>There is some fixed overhead per object. It's JVM-specific, but I usually estimate 40 bytes. Then you have to look at the members of the class. Object references are 4 (8) bytes in a 32-bit (64-bit) JVM. Primitive types are: </p>\n\n<ul>\n<li>boolean and byte: 1 byte</li>\n<li>char and short: 2 bytes</li>\n<li>int and float: 4 bytes</li>\n<li>long and double: 8 bytes</li>\n</ul>\n\n<p>Arrays follow the same rules; that is, it's an object reference so that takes 4 (or 8) bytes in your object, and then its length multiplied by the size of its element.</p>\n\n<p>Trying to do it programmatically with calls to <code>Runtime.freeMemory()</code> just doesn't give you much accuracy, because of asynchronous calls to the garbage collector, etc. Profiling the heap with -Xrunhprof or other tools will give you the most accurate results.</p>\n"}, {'answer_id': 52401, 'author': 'Nick Fortescue', 'author_id': 5346, 'author_profile': 'https://Stackoverflow.com/users/5346', 'pm_score': 6, 'selected': False, 'text': '<p>Firstly "the size of an object" isn\'t a well-defined concept in Java. You could mean the object itself, with just its members, the Object and all objects it refers to (the reference graph). You could mean the size in memory or the size on disk. And the JVM is allowed to optimise things like Strings.</p>\n\n<p>So the only correct way is to ask the JVM, with a good profiler (I use <a href="http://www.yourkit.com" rel="noreferrer">YourKit</a>), which probably isn\'t what you want.</p>\n\n<p>However, from the description above it sounds like each row will be self-contained, and not have a big dependency tree, so the serialization method will probably be a good approximation on most JVMs. The easiest way to do this is as follows:</p>\n\n<pre><code> Serializable ser;\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(ser);\n oos.close();\n return baos.size();\n</code></pre>\n\n<p>Remember that if you have objects with common references this <em>will not</em> give the correct result, and size of serialization will not always match size in memory, but it is a good approximation. The code will be a bit more efficient if you initialise the ByteArrayOutputStream size to a sensible value.</p>\n'}, {'answer_id': 52568, 'author': 'Boris Terzic', 'author_id': 1996, 'author_profile': 'https://Stackoverflow.com/users/1996', 'pm_score': 6, 'selected': False, 'text': '<p>Some years back Javaworld had <a href="https://www.infoworld.com/article/2077408/sizeof-for-java.html" rel="noreferrer">an article on determining the size of composite and potentially nested Java objects</a>, they basically walk through creating a sizeof() implementation in Java. The approach basically builds on other work where people experimentally identified the size of primitives and typical Java objects and then apply that knowledge to a method that recursively walks an object graph to tally the total size.</p>\n<p>It is always going to be somewhat less accurate than a native C implementation simply because of the things going on behind the scenes of a class but it should be a good indicator.</p>\n<p>Alternatively a SourceForge project appropriately called <a href="http://sourceforge.net/projects/sizeof" rel="noreferrer">sizeof</a> that offers a Java5 library with a sizeof() implementation.</p>\n<p>P.S. Do not use the serialization approach, there is no correlation between the size of a serialized object and the amount of memory it consumes when live.</p>\n'}, {'answer_id': 52682, 'author': 'Stefan Karlsson', 'author_id': 5438, 'author_profile': 'https://Stackoverflow.com/users/5438', 'pm_score': 10, 'selected': True, 'text': '<p>You can use the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html" rel="noreferrer"><code>java.lang.instrument</code> package</a>.</p>\n<p>Compile and put this class in a JAR:</p>\n<pre><code>import java.lang.instrument.Instrumentation;\n\npublic class ObjectSizeFetcher {\n    private static Instrumentation instrumentation;\n\n    public static void premain(String args, Instrumentation inst) {\n        instrumentation = inst;\n    }\n\n    public static long getObjectSize(Object o) {\n        return instrumentation.getObjectSize(o);\n    }\n}\n</code></pre>\n<p>Add the following to your <code>MANIFEST.MF</code>:</p>\n<pre><code>Premain-Class: ObjectSizeFetcher\n</code></pre>\n<p>Use the <code>getObjectSize()</code> method:</p>\n<pre><code>public class C {\n    private int x;\n    private int y;\n\n    public static void main(String [] args) {\n        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));\n    }\n}\n</code></pre>\n<p>Invoke with:</p>\n<pre><code>java -javaagent:ObjectSizeFetcherAgent.jar C\n</code></pre>\n'}, {'answer_id': 10587479, 'author': 'Miguel Gamboa', 'author_id': 1140754, 'author_profile': 'https://Stackoverflow.com/users/1140754', 'pm_score': 3, 'selected': False, 'text': '<p>The <code>java.lang.instrument.Instrumentation</code> class provides a nice way to get the size of a Java Object, but it requires you to define a <code>premain</code> and run your program with a java agent. This is very boring when you do not need any agent and then you have to provide a dummy Jar agent to your application.</p>\n\n<p>So I got an alternative solution using the <code>Unsafe</code> class from the <code>sun.misc</code>. So, considering the objects heap alignment according to the processor architecture and calculating the maximum field offset, you can measure the size of a Java Object. In the example below I use an auxiliary class <code>UtilUnsafe</code> to get a reference to the <code>sun.misc.Unsafe</code> object.</p>\n\n<pre><code>private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model"));\nprivate static final int BYTE = 8;\nprivate static final int WORD = NR_BITS/BYTE;\nprivate static final int MIN_SIZE = 16; \n\npublic static int sizeOf(Class src){\n    //\n    // Get the instance fields of src class\n    // \n    List&lt;Field&gt; instanceFields = new LinkedList&lt;Field&gt;();\n    do{\n        if(src == Object.class) return MIN_SIZE;\n        for (Field f : src.getDeclaredFields()) {\n            if((f.getModifiers() &amp; Modifier.STATIC) == 0){\n                instanceFields.add(f);\n            }\n        }\n        src = src.getSuperclass();\n    }while(instanceFields.isEmpty());\n    //\n    // Get the field with the maximum offset\n    //  \n    long maxOffset = 0;\n    for (Field f : instanceFields) {\n        long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f);\n        if(offset &gt; maxOffset) maxOffset = offset; \n    }\n    return  (((int)maxOffset/WORD) + 1)*WORD; \n}\nclass UtilUnsafe {\n    public static final sun.misc.Unsafe UNSAFE;\n\n    static {\n        Object theUnsafe = null;\n        Exception exception = null;\n        try {\n            Class&lt;?&gt; uc = Class.forName("sun.misc.Unsafe");\n            Field f = uc.getDeclaredField("theUnsafe");\n            f.setAccessible(true);\n            theUnsafe = f.get(uc);\n        } catch (Exception e) { exception = e; }\n        UNSAFE = (sun.misc.Unsafe) theUnsafe;\n        if (UNSAFE == null) throw new Error("Could not obtain access to sun.misc.Unsafe", exception);\n    }\n    private UtilUnsafe() { }\n}\n</code></pre>\n'}, {'answer_id': 15815016, 'author': 'JZeeb', 'author_id': 161142, 'author_profile': 'https://Stackoverflow.com/users/161142', 'pm_score': 0, 'selected': False, 'text': '<p>You could generate a heap dump (with jmap, for example) and then analyze the output to find object sizes.  This is an offline solution, but you can examine shallow and deep sizes, etc.</p>\n'}, {'answer_id': 18645101, 'author': 'PNS', 'author_id': 834316, 'author_profile': 'https://Stackoverflow.com/users/834316', 'pm_score': 3, 'selected': False, 'text': '<p>There is also the <strong>Memory Measurer</strong> tool (formerly at <a href="http://code.google.com/p/memory-measurer/" rel="nofollow noreferrer">Google Code</a>, now on <a href="https://github.com/DimitrisAndreou/memory-measurer" rel="nofollow noreferrer">GitHub</a>), which is simple and published under the commercial-friendly <strong>Apache 2.0 license</strong>, as discussed in a <a href="https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java">similar question</a>.</p>\n\n<p>It, too, requires a command-line argument to the java interpreter if you want to measure memory byte consumption, but otherwise seems to work just fine, at least in the scenarios I have used it.</p>\n'}, {'answer_id': 20014332, 'author': 'Jason C', 'author_id': 616460, 'author_profile': 'https://Stackoverflow.com/users/616460', 'pm_score': 2, 'selected': False, 'text': '<p>I wrote a quick test once to estimate on the fly:</p>\n\n<pre><code>public class Test1 {\n\n    // non-static nested\n    class Nested { }\n\n    // static nested\n    static class StaticNested { }\n\n    static long getFreeMemory () {\n        // waits for free memory measurement to stabilize\n        long init = Runtime.getRuntime().freeMemory(), init2;\n        int count = 0;\n        do {\n            System.out.println("waiting..." + init);\n            System.gc();\n            try { Thread.sleep(250); } catch (Exception x) { }\n            init2 = init;\n            init = Runtime.getRuntime().freeMemory();\n            if (init == init2) ++ count; else count = 0;\n        } while (count &lt; 5);\n        System.out.println("ok..." + init);\n        return init;\n    }\n\n    Test1 () throws InterruptedException {\n\n        Object[] s = new Object[10000];\n        Object[] n = new Object[10000];\n        Object[] t = new Object[10000];\n\n        long init = getFreeMemory();\n\n        //for (int j = 0; j &lt; 10000; ++ j)\n        //    s[j] = new Separate();\n\n        long afters = getFreeMemory();\n\n        for (int j = 0; j &lt; 10000; ++ j)\n            n[j] = new Nested();\n\n        long aftersn = getFreeMemory();\n\n        for (int j = 0; j &lt; 10000; ++ j)\n            t[j] = new StaticNested();\n\n        long aftersnt = getFreeMemory();\n\n        System.out.println("separate:      " + -(afters - init) + " each=" + -(afters - init) / 10000);\n        System.out.println("nested:        " + -(aftersn - afters) + " each=" + -(aftersn - afters) / 10000);\n        System.out.println("static nested: " + -(aftersnt - aftersn) + " each=" + -(aftersnt - aftersn) / 10000);\n\n    }\n\n    public static void main (String[] args) throws InterruptedException {\n        new Test1();\n    }\n\n}\n</code></pre>\n\n<p>General concept is allocate objects and measure change in free heap space. The key being <code>getFreeMemory()</code>, which <strong>requests GC runs and waits for the reported free heap size to stabilize</strong>. The output of the above is:</p>\n\n<pre><code>nested:        160000 each=16\nstatic nested: 160000 each=16\n</code></pre>\n\n<p>Which is what we expect, given alignment behavior and possible heap block header overhead.</p>\n\n<p>The instrumentation method detailed in the accepted answer here the most accurate. The method I described is accurate but only under controlled conditions where no other threads are creating/discarding objects.</p>\n'}, {'answer_id': 23511330, 'author': 'user835199', 'author_id': 835199, 'author_profile': 'https://Stackoverflow.com/users/835199', 'pm_score': 1, 'selected': False, 'text': '<pre><code>long heapSizeBefore = Runtime.getRuntime().totalMemory();\n\n// Code for object construction\n...\nlong heapSizeAfter = Runtime.getRuntime().totalMemory();\nlong size = heapSizeAfter - heapSizeBefore;\n</code></pre>\n\n<p>size gives you the increase in memory usage of the jvm due to object creation and that typically is the size of the object.</p>\n'}, {'answer_id': 24423089, 'author': 'dlaudams', 'author_id': 3777283, 'author_profile': 'https://Stackoverflow.com/users/3777283', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a utility I made using some of the linked examples to handle 32-bit, 64-bit and 64-bit with compressed OOP. It uses <code>sun.misc.Unsafe</code>.</p>\n\n<p>It uses <code>Unsafe.addressSize()</code> to get the size of a native pointer and <code>Unsafe.arrayIndexScale( Object[].class )</code> for the size of a Java reference.</p>\n\n<p>It uses the field offset of a known class to work out the base size of an object.</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.IdentityHashMap;\nimport java.util.Stack;\nimport sun.misc.Unsafe;\n\n/** Usage: \n * MemoryUtil.sizeOf( object )\n * MemoryUtil.deepSizeOf( object )\n * MemoryUtil.ADDRESS_MODE\n */\npublic class MemoryUtil\n{\n    private MemoryUtil()\n    {\n    }\n\n    public static enum AddressMode\n    {\n        /** Unknown address mode. Size calculations may be unreliable. */\n        UNKNOWN,\n        /** 32-bit address mode using 32-bit references. */\n        MEM_32BIT,\n        /** 64-bit address mode using 64-bit references. */\n        MEM_64BIT,\n        /** 64-bit address mode using 32-bit compressed references. */\n        MEM_64BIT_COMPRESSED_OOPS\n    }\n\n    /** The detected runtime address mode. */\n    public static final AddressMode ADDRESS_MODE;\n\n    private static final Unsafe UNSAFE;\n\n    private static final long ADDRESS_SIZE; // The size in bytes of a native pointer: 4 for 32 bit, 8 for 64 bit\n    private static final long REFERENCE_SIZE; // The size of a Java reference: 4 for 32 bit, 4 for 64 bit compressed oops, 8 for 64 bit\n    private static final long OBJECT_BASE_SIZE; // The minimum size of an Object: 8 for 32 bit, 12 for 64 bit compressed oops, 16 for 64 bit\n    private static final long OBJECT_ALIGNMENT = 8;\n\n    /** Use the offset of a known field to determine the minimum size of an object. */\n    private static final Object HELPER_OBJECT = new Object() { byte b; };\n\n\n    static\n    {\n        try\n        {\n            // Use reflection to get a reference to the \'Unsafe\' object.\n            Field f = Unsafe.class.getDeclaredField( "theUnsafe" );\n            f.setAccessible( true );\n            UNSAFE = (Unsafe) f.get( null );\n\n            OBJECT_BASE_SIZE = UNSAFE.objectFieldOffset( HELPER_OBJECT.getClass().getDeclaredField( "b" ) );\n\n            ADDRESS_SIZE = UNSAFE.addressSize();\n            REFERENCE_SIZE = UNSAFE.arrayIndexScale( Object[].class );\n\n            if( ADDRESS_SIZE == 4 )\n            {\n                ADDRESS_MODE = AddressMode.MEM_32BIT;\n            }\n            else if( ADDRESS_SIZE == 8 &amp;&amp; REFERENCE_SIZE == 8 )\n            {\n                ADDRESS_MODE = AddressMode.MEM_64BIT;\n            }\n            else if( ADDRESS_SIZE == 8 &amp;&amp; REFERENCE_SIZE == 4 )\n            {\n                ADDRESS_MODE = AddressMode.MEM_64BIT_COMPRESSED_OOPS;\n            }\n            else\n            {\n                ADDRESS_MODE = AddressMode.UNKNOWN;\n            }\n        }\n        catch( Exception e )\n        {\n            throw new Error( e );\n        }\n    }\n\n\n    /** Return the size of the object excluding any referenced objects. */\n    public static long shallowSizeOf( final Object object )\n    {\n        Class&lt;?&gt; objectClass = object.getClass();\n        if( objectClass.isArray() )\n        {\n            // Array size is base offset + length * element size\n            long size = UNSAFE.arrayBaseOffset( objectClass )\n                    + UNSAFE.arrayIndexScale( objectClass ) * Array.getLength( object );\n            return padSize( size );\n        }\n        else\n        {\n            // Object size is the largest field offset padded out to 8 bytes\n            long size = OBJECT_BASE_SIZE;\n            do\n            {\n                for( Field field : objectClass.getDeclaredFields() )\n                {\n                    if( (field.getModifiers() &amp; Modifier.STATIC) == 0 )\n                    {\n                        long offset = UNSAFE.objectFieldOffset( field );\n                        if( offset &gt;= size )\n                        {\n                            size = offset + 1; // Field size is between 1 and PAD_SIZE bytes. Padding will round up to padding size.\n                        }\n                    }\n                }\n                objectClass = objectClass.getSuperclass();\n            }\n            while( objectClass != null );\n\n            return padSize( size );\n        }\n    }\n\n\n    private static final long padSize( final long size )\n    {\n        return (size + (OBJECT_ALIGNMENT - 1)) &amp; ~(OBJECT_ALIGNMENT - 1);\n    }\n\n\n    /** Return the size of the object including any referenced objects. */\n    public static long deepSizeOf( final Object object )\n    {\n        IdentityHashMap&lt;Object,Object&gt; visited = new IdentityHashMap&lt;Object,Object&gt;();\n        Stack&lt;Object&gt; stack = new Stack&lt;Object&gt;();\n        if( object != null ) stack.push( object );\n\n        long size = 0;\n        while( !stack.isEmpty() )\n        {\n            size += internalSizeOf( stack.pop(), stack, visited );\n        }\n        return size;\n    }\n\n\n    private static long internalSizeOf( final Object object, final Stack&lt;Object&gt; stack, final IdentityHashMap&lt;Object,Object&gt; visited )\n    {\n        // Scan for object references and add to stack\n        Class&lt;?&gt; c = object.getClass();\n        if( c.isArray() &amp;&amp; !c.getComponentType().isPrimitive() )\n        {\n            // Add unseen array elements to stack\n            for( int i = Array.getLength( object ) - 1; i &gt;= 0; i-- )\n            {\n                Object val = Array.get( object, i );\n                if( val != null &amp;&amp; visited.put( val, val ) == null )\n                {\n                    stack.add( val );\n                }\n            }\n        }\n        else\n        {\n            // Add unseen object references to the stack\n            for( ; c != null; c = c.getSuperclass() )\n            {\n                for( Field field : c.getDeclaredFields() )\n                {\n                    if( (field.getModifiers() &amp; Modifier.STATIC) == 0 \n                            &amp;&amp; !field.getType().isPrimitive() )\n                    {\n                        field.setAccessible( true );\n                        try\n                        {\n                            Object val = field.get( object );\n                            if( val != null &amp;&amp; visited.put( val, val ) == null )\n                            {\n                                stack.add( val );\n                            }\n                        }\n                        catch( IllegalArgumentException e )\n                        {\n                            throw new RuntimeException( e );\n                        }\n                        catch( IllegalAccessException e )\n                        {\n                            throw new RuntimeException( e );\n                        }\n                    }\n                }\n            }\n        }\n\n        return shallowSizeOf( object );\n    }\n}\n</code></pre>\n'}, {'answer_id': 26407668, 'author': 'Agnius Vasiliauskas', 'author_id': 380331, 'author_profile': 'https://Stackoverflow.com/users/380331', 'pm_score': 1, 'selected': False, 'text': '<p>My answer is based on the code supplied by Nick. That code measures total amount of bytes which are occupied by the serialized object. So this actually measures serialization stuff + plain object memory footprint (just serialize for example <code>int</code> and you will see that total amount of serialized bytes is not <code>4</code>). So if you want to get raw byte number used exactly for your object - you need to modify that code a bit. Like so:</p>\n\n<pre><code>import java.io.ByteArrayOutputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\npublic class ObjectSizeCalculator {\n    private Object getFirstObjectReference(Object o) {\n        String objectType = o.getClass().getTypeName();\n\n        if (objectType.substring(objectType.length()-2).equals("[]")) {\n            try {\n                if (objectType.equals("java.lang.Object[]"))\n                    return ((Object[])o)[0];\n                else if (objectType.equals("int[]"))\n                    return ((int[])o)[0];\n                else\n                    throw new RuntimeException("Not Implemented !");\n            } catch (IndexOutOfBoundsException e) {\n                return null;\n            }\n        }\n\n        return o;\n    } \n\n    public int getObjectSizeInBytes(Object o) {\n        final String STRING_JAVA_TYPE_NAME = "java.lang.String";\n\n        if (o == null)\n            return 0;\n\n        String objectType = o.getClass().getTypeName();\n        boolean isArray = objectType.substring(objectType.length()-2).equals("[]");\n\n        Object objRef = getFirstObjectReference(o);\n        if (objRef != null &amp;&amp; !(objRef instanceof Serializable))\n            throw new RuntimeException("Object must be serializable for measuring it\'s memory footprint using this method !");\n\n        try {\n            ByteArrayOutputStream baos = new ByteArrayOutputStream();\n            ObjectOutputStream oos = new ObjectOutputStream(baos);\n            oos.writeObject(o);\n            oos.close();\n            byte[] bytes = baos.toByteArray();\n\n            for (int i = bytes.length - 1, j = 0; i != 0; i--, j++) {\n                if (objectType != STRING_JAVA_TYPE_NAME) {\n                    if (bytes[i] == 112)\n                        if (isArray)\n                            return j - 4;\n                        else\n                            return j;\n                } else {\n                    if (bytes[i] == 0)\n                        return j - 1;\n                }\n            }\n        } catch (Exception e) {\n            return -1;\n        }\n\n        return -1;\n    }    \n\n}\n</code></pre>\n\n<p>I\'ve tested this solution with primitive types, String, and on some trivial classes. There may be not covered cases also.</p>\n\n<p><br><strong>UPDATE:</strong> Example modified to support memory footprint calculation of array objects.</p>\n'}, {'answer_id': 28825937, 'author': 'Kanagavelu Sugumar', 'author_id': 912319, 'author_profile': 'https://Stackoverflow.com/users/912319', 'pm_score': 1, 'selected': False, 'text': "<p>This answer is not related to Object size, but when you are using array to accommodate the objects; how much memory size it will allocate for the object.</p>\n\n<p>So arrays, list, or map all those collection won't be going to store objects really (only at the time of primitives, real object memory size is needed), it will store only references for those objects. </p>\n\n<p>Now the <code>Used heap memory = sizeOfObj + sizeOfRef (* 4 bytes) in collection</code></p>\n\n<ul>\n<li>(4/8 bytes) depends on (32/64 bit) OS</li>\n</ul>\n\n<p><strong>PRIMITIVES</strong></p>\n\n<pre><code>int   [] intArray    = new int   [1]; will require 4 bytes.\nlong  [] longArray   = new long  [1]; will require 8 bytes.\n</code></pre>\n\n<p><strong>OBJECTS</strong></p>\n\n<pre><code>Object[] objectArray = new Object[1]; will require 4 bytes. The object can be any user defined Object.\nLong  [] longArray   = new Long  [1]; will require 4 bytes.\n</code></pre>\n\n<p>I mean to say all the object REFERENCE needs only 4 bytes of memory. It may be String reference OR Double object reference, But depends on object creation the memory needed will vary.</p>\n\n<p>e.g) If i create object for the below class <code>ReferenceMemoryTest</code> then 4 + 4 + 4 = 12 bytes of memory will be created. The memory may differ when you are trying to initialize the references.</p>\n\n<pre><code> class ReferenceMemoryTest {\n    public String refStr;\n    public Object refObj;\n    public Double refDoub; \n}\n</code></pre>\n\n<p>So when are creating object/reference array, all its contents will be occupied with NULL references. And we know each reference requires 4 bytes.</p>\n\n<p>And finally, memory allocation for the below code is 20 bytes.</p>\n\n<p>ReferenceMemoryTest ref1 = new ReferenceMemoryTest(); ( 4(ref1) + 12 = 16 bytes)\nReferenceMemoryTest ref2 = ref1;                      ( 4(ref2) + 16 = 20 bytes)</p>\n"}, {'answer_id': 28900509, 'author': 'rich', 'author_id': 180416, 'author_profile': 'https://Stackoverflow.com/users/180416', 'pm_score': 5, 'selected': False, 'text': '<p>Much of the other answers provide shallow sizes - e.g. the size of a HashMap without any of the keys or values, which isn\'t likely what you want.</p>\n\n<p>The jamm project uses the java.lang.instrumentation package above but walks the tree and so can give you the deep memory use.</p>\n\n<pre><code>new MemoryMeter().measureDeep(myHashMap);\n</code></pre>\n\n<p><a href="https://github.com/jbellis/jamm" rel="noreferrer">https://github.com/jbellis/jamm</a></p>\n\n<blockquote>\n  <p>To use MemoryMeter, start the JVM with "-javaagent:/jamm.jar"</p>\n</blockquote>\n'}, {'answer_id': 29431949, 'author': 'reallynice', 'author_id': 1504300, 'author_profile': 'https://Stackoverflow.com/users/1504300', 'pm_score': 2, 'selected': False, 'text': '<p>Without having to mess with instrumentation and so on, and if you don\'t need to know the byte-exact size of an object, you could go with the following approach:</p>\n\n<pre><code>System.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n\ndo your job here\n\nSystem.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>This way you read the used memory before and after, and calling the GC just before getting the used memory you lower the "noise" almost to 0.</p>\n\n<p>For a more reliable result you can run your job n times, and then divide the used memory by n, obtaining how much memory one run takes. Even more, you can run the whole thing more times and make an average.</p>\n'}, {'answer_id': 29536817, 'author': 'Attila Szegedi', 'author_id': 131552, 'author_profile': 'https://Stackoverflow.com/users/131552', 'pm_score': 5, 'selected': False, 'text': '<p>Back when I worked at Twitter, I wrote a utility for calculating deep object size. It takes into account different memory models (32-bit, compressed oops, 64-bit), padding, subclass padding, works correctly on circular data structures and arrays. You can just compile this one .java file; it has no external dependencies:</p>\n\n<p><a href="https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java" rel="noreferrer">https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java</a></p>\n'}, {'answer_id': 30021105, 'author': 'Jeffrey Bosboom', 'author_id': 3614835, 'author_profile': 'https://Stackoverflow.com/users/3614835', 'pm_score': 7, 'selected': False, 'text': '<p>You should use <a href="http://openjdk.java.net/projects/code-tools/jol/" rel="noreferrer">jol</a>, a tool developed as part of the OpenJDK project.</p>\n\n<blockquote>\n  <p>JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layout, footprint, and references. This makes JOL much more accurate than other tools relying on heap dumps, specification assumptions, etc.</p>\n</blockquote>\n\n<p>To get the sizes of primitives, references and array elements, use <code>VMSupport.vmDetails()</code>.  On Oracle JDK 1.8.0_40 running on 64-bit Windows (used for all following examples), this method returns</p>\n\n<pre><code>Running 64-bit HotSpot VM.\nUsing compressed oop with 0-bit shift.\nUsing compressed klass with 3-bit shift.\nObjects are 8 bytes aligned.\nField sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\nArray element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\n</code></pre>\n\n<p>You can get the shallow size of an object instance using <code>ClassLayout.parseClass(Foo.class).toPrintable()</code> (optionally passing an instance to <code>toPrintable</code>).  This is only the space consumed by a single instance of that class; it does not include any other objects referenced by that class.  It <em>does</em> include VM overhead for the object header, field alignment and padding.  For <code>java.util.regex.Pattern</code>:</p>\n\n<pre><code>java.util.regex.Pattern object internals:\n OFFSET  SIZE        TYPE DESCRIPTION                    VALUE\n      0     4             (object header)                01 00 00 00 (0000 0001 0000 0000 0000 0000 0000 0000)\n      4     4             (object header)                00 00 00 00 (0000 0000 0000 0000 0000 0000 0000 0000)\n      8     4             (object header)                cb cf 00 20 (1100 1011 1100 1111 0000 0000 0010 0000)\n     12     4         int Pattern.flags                  0\n     16     4         int Pattern.capturingGroupCount    1\n     20     4         int Pattern.localCount             0\n     24     4         int Pattern.cursor                 48\n     28     4         int Pattern.patternLength          0\n     32     1     boolean Pattern.compiled               true\n     33     1     boolean Pattern.hasSupplementary       false\n     34     2             (alignment/padding gap)        N/A\n     36     4      String Pattern.pattern                (object)\n     40     4      String Pattern.normalizedPattern      (object)\n     44     4        Node Pattern.root                   (object)\n     48     4        Node Pattern.matchRoot              (object)\n     52     4       int[] Pattern.buffer                 null\n     56     4         Map Pattern.namedGroups            null\n     60     4 GroupHead[] Pattern.groupNodes             null\n     64     4       int[] Pattern.temp                   null\n     68     4             (loss due to the next object alignment)\nInstance size: 72 bytes (reported by Instrumentation API)\nSpace losses: 2 bytes internal + 4 bytes external = 6 bytes total\n</code></pre>\n\n<p>You can get a summary view of the deep size of an object instance using <code>GraphLayout.parseInstance(obj).toFootprint()</code>.  Of course, some objects in the footprint might be shared (also referenced from other objects), so it is an overapproximation of the space that could be reclaimed when that object is garbage collected.  For the result of <code>Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$")</code> (taken from <a href="https://stackoverflow.com/a/719543/3614835">this answer</a>), jol reports a total footprint of 1840 bytes, of which only 72 are the Pattern instance itself.</p>\n\n<pre><code>java.util.regex.Pattern instance footprint:\n     COUNT       AVG       SUM   DESCRIPTION\n         1       112       112   [C\n         3       272       816   [Z\n         1        24        24   java.lang.String\n         1        72        72   java.util.regex.Pattern\n         9        24       216   java.util.regex.Pattern$1\n        13        24       312   java.util.regex.Pattern$5\n         1        16        16   java.util.regex.Pattern$Begin\n         3        24        72   java.util.regex.Pattern$BitClass\n         3        32        96   java.util.regex.Pattern$Curly\n         1        24        24   java.util.regex.Pattern$Dollar\n         1        16        16   java.util.regex.Pattern$LastNode\n         1        16        16   java.util.regex.Pattern$Node\n         2        24        48   java.util.regex.Pattern$Single\n        40                1840   (total)\n</code></pre>\n\n<p>If you instead use <code>GraphLayout.parseInstance(obj).toPrintable()</code>, jol will tell you the address, size, type, value and path of field dereferences to each referenced object, though that\'s usually too much detail to be useful.  For the ongoing pattern example, you might get the following.  (Addresses will likely change between runs.)</p>\n\n<pre><code>java.util.regex.Pattern object externals:\n          ADDRESS       SIZE TYPE                             PATH                           VALUE\n         d5e5f290         16 java.util.regex.Pattern$Node     .root.next.atom.next           (object)\n         d5e5f2a0        120 (something else)                 (somewhere else)               (something else)\n         d5e5f318         16 java.util.regex.Pattern$LastNode .root.next.next.next.next.next.next.next (object)\n         d5e5f328      21664 (something else)                 (somewhere else)               (something else)\n         d5e647c8         24 java.lang.String                 .pattern                       (object)\n         d5e647e0        112 [C                               .pattern.value                 [^, [, a, -, z, A, -, Z, 0, -, 9, _, ., +, -, ], +, @, [, a, -, z, A, -, Z, 0, -, 9, -, ], +, \\, ., [, a, -, z, A, -, Z, 0, -, 9, -, ., ], +, $]\n         d5e64850        448 (something else)                 (somewhere else)               (something else)\n         d5e64a10         72 java.util.regex.Pattern                                         (object)\n         d5e64a58        416 (something else)                 (somewhere else)               (something else)\n         d5e64bf8         16 java.util.regex.Pattern$Begin    .root                          (object)\n         d5e64c08         24 java.util.regex.Pattern$BitClass .root.next.atom.val$rhs        (object)\n         d5e64c20        272 [Z                               .root.next.atom.val$rhs.bits   [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n         d5e64d30         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n         d5e64d48         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n         d5e64d60         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n         d5e64d78         24 java.util.regex.Pattern$1        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n         d5e64d90         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n         d5e64da8         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs.val$lhs (object)\n         d5e64dc0         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs.val$lhs (object)\n         d5e64dd8         24 java.util.regex.Pattern$5        .root.next.atom.val$lhs        (object)\n         d5e64df0         24 java.util.regex.Pattern$5        .root.next.atom                (object)\n         d5e64e08         32 java.util.regex.Pattern$Curly    .root.next                     (object)\n         d5e64e28         24 java.util.regex.Pattern$Single   .root.next.next                (object)\n         d5e64e40         24 java.util.regex.Pattern$BitClass .root.next.next.next.atom.val$rhs (object)\n         d5e64e58        272 [Z                               .root.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n         d5e64f68         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n         d5e64f80         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n         d5e64f98         24 java.util.regex.Pattern$5        .root.next.next.next.atom.val$lhs.val$lhs (object)\n         d5e64fb0         24 java.util.regex.Pattern$1        .root.next.next.next.atom.val$lhs.val$rhs (object)\n         d5e64fc8         24 java.util.regex.Pattern$5        .root.next.next.next.atom.val$lhs (object)\n         d5e64fe0         24 java.util.regex.Pattern$5        .root.next.next.next.atom      (object)\n         d5e64ff8         32 java.util.regex.Pattern$Curly    .root.next.next.next           (object)\n         d5e65018         24 java.util.regex.Pattern$Single   .root.next.next.next.next      (object)\n         d5e65030         24 java.util.regex.Pattern$BitClass .root.next.next.next.next.next.atom.val$rhs (object)\n         d5e65048        272 [Z                               .root.next.next.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n         d5e65158         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n         d5e65170         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$rhs (object)\n         d5e65188         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n         d5e651a0         24 java.util.regex.Pattern$1        .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n         d5e651b8         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs.val$lhs (object)\n         d5e651d0         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom.val$lhs (object)\n         d5e651e8         24 java.util.regex.Pattern$5        .root.next.next.next.next.next.atom (object)\n         d5e65200         32 java.util.regex.Pattern$Curly    .root.next.next.next.next.next (object)\n         d5e65220        120 (something else)                 (somewhere else)               (something else)\n         d5e65298         24 java.util.regex.Pattern$Dollar   .root.next.next.next.next.next.next (object)\n</code></pre>\n\n<p>The "(something else)" entries <a href="https://stackoverflow.com/questions/30021092/what-is-something-else-in-jol-graphlayout-output">describe other objects in the heap that are not part of this object graph</a>.</p>\n\n<p>The best jol documentation is the <a href="http://hg.openjdk.java.net/code-tools/jol/file/tip/jol-samples/src/main/java/org/openjdk/jol/samples/" rel="noreferrer">jol samples</a> in the jol repository.  The samples demonstrate common jol operations and show how you can use jol to analyze VM and garbage collector internals.</p>\n'}, {'answer_id': 39406536, 'author': 'Tom', 'author_id': 1762932, 'author_profile': 'https://Stackoverflow.com/users/1762932', 'pm_score': 7, 'selected': False, 'text': '<p>I accidentally found a java class\n"jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", already in jdk, \nwhich is easy to use and seems quite useful for determining the size of an object.</p>\n\n<pre><code>System.out.println(ObjectSizeCalculator.getObjectSize(new gnu.trove.map.hash.TObjectIntHashMap&lt;String&gt;(12000, 0.6f, -1)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new HashMap&lt;String, Integer&gt;(100000)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(3));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 }));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[100]));\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>164192\n48\n16\n48\n416\n</code></pre>\n'}, {'answer_id': 47848790, 'author': 'Sai Kiran', 'author_id': 7706962, 'author_profile': 'https://Stackoverflow.com/users/7706962', 'pm_score': -1, 'selected': False, 'text': '<p>For JSONObject the below code can help you.</p>\n\n<pre><code>`JSONObject.toString().getBytes("UTF-8").length`\n</code></pre>\n\n<p>returns size in bytes</p>\n\n<p>I checked it with my JSONArray object by writing it to a file. It is giving object size.</p>\n'}, {'answer_id': 49449106, 'author': 'ACV', 'author_id': 912829, 'author_profile': 'https://Stackoverflow.com/users/912829', 'pm_score': 2, 'selected': False, 'text': '<p>Just use java visual VM. </p>\n\n<p>It has everything you need to profile and debug memory problems. </p>\n\n<p>It also has a OQL (Object Query Language) console which allows you to do many useful things, one of which being <code>sizeof(o)</code></p>\n'}, {'answer_id': 55404104, 'author': 'Ali Dehghani', 'author_id': 1393484, 'author_profile': 'https://Stackoverflow.com/users/1393484', 'pm_score': 0, 'selected': False, 'text': '<p>Suppose I declare a class named <code>Complex</code> like:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class Complex {\n\n    private final long real;\n    private final long imaginary;\n\n    // omitted\n}\n\n</code></pre>\n\n<p>In order to see how much memory is allocated to live instances of this class:</p>\n\n<pre class="lang-sh prettyprint-override"><code>$ jmap -histo:live &lt;pid&gt; | grep Complex\n\n num     #instances         #bytes  class name (module)\n-------------------------------------------------------\n 327:             1             32  Complex\n</code></pre>\n'}, {'answer_id': 56783991, 'author': 'David Ryan', 'author_id': 5307079, 'author_profile': 'https://Stackoverflow.com/users/5307079', 'pm_score': 2, 'selected': False, 'text': '<p>I was looking for a runtime calculation of an object size that met the following requirements:</p>\n<ul>\n<li>Available at runtime with no need to include instrumentation.</li>\n<li>Works with Java 9+ without access to Unsafe.</li>\n<li>Is based on the Class only. Not a deep sizeOf that takes into consideration string lengths, array lengths, etc.</li>\n</ul>\n<p>The following is based on the core code of the original java specialists article (<a href="https://www.javaspecialists.eu/archive/Issue078.html" rel="nofollow noreferrer">https://www.javaspecialists.eu/archive/Issue078.html</a>) and a few bits from the Unsafe version in another answer to this question.</p>\n<p>I hope someone finds it useful.</p>\n<pre><code>public class JavaSize {\n\n    private static final int NR_BITS = Integer.valueOf(System.getProperty(&quot;sun.arch.data.model&quot;));\n    private static final int BYTE = 8;\n    private static final int WORD = NR_BITS / BYTE;\n    private static final int HEADER_SIZE = 8;\n\n    public static int sizeOf(Class&lt;?&gt; clazz) {\n        int result = 0;\n\n        while (clazz != null) {\n            Field[] fields = clazz.getDeclaredFields();\n            for (int i = 0; i &lt; fields.length; i++) {\n                if (!Modifier.isStatic(fields[i].getModifiers())) {\n                    if (fields[i].getType().isPrimitive()) {\n                        Class&lt;?&gt; primitiveClass = fields[i].getType();\n                        if (primitiveClass == boolean.class || primitiveClass == byte.class) {\n                            result += 1;\n                        } else if (primitiveClass == short.class) {\n                            result += 2;\n                        } else if (primitiveClass == int.class || primitiveClass == float.class) {\n                            result += 4;\n                        } else if (primitiveClass == double.class || primitiveClass == long.class) {\n                            result += 8;\n                        }\n\n                    } else {\n                        // assume compressed references.\n                        result += 4;\n                    }\n                }\n            }\n\n            clazz = clazz.getSuperclass();\n\n            // round up to the nearest WORD length.\n            if ((result % WORD) != 0) {\n                result += WORD - (result % WORD);\n            }\n        }\n\n        result += HEADER_SIZE;\n\n        return result;\n    }\n }\n</code></pre>\n'}, {'answer_id': 61397323, 'author': 'simon04', 'author_id': 205629, 'author_profile': 'https://Stackoverflow.com/users/205629', 'pm_score': 4, 'selected': False, 'text': '<p>When using JetBrains IntelliJ, first enable "Attach memory agent" in File | Settings | Build, Execution, Deployment | Debugger.</p>\n\n<p>When debugging, right-click a variable of interest and choose "Calculate Retained Size": <a href="https://i.stack.imgur.com/TvMel.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TvMel.png" alt="Calculate Retained Size"></a></p>\n'}, {'answer_id': 71230694, 'author': 'Maurice', 'author_id': 6351733, 'author_profile': 'https://Stackoverflow.com/users/6351733', 'pm_score': 0, 'selected': False, 'text': '<p>If your application has the <a href="https://www.baeldung.com/java-commons-lang-3" rel="nofollow noreferrer">Apache commons lang library</a> as a dependency or is using the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/SerializationUtils.html" rel="nofollow noreferrer">Spring framework</a> then you can also use the <code>SerializationUtils</code> class to quickly find out the approximate byte size of any given object.</p>\n<pre><code>byte[] data = SerializationUtils.serialize(user);\nSystem.out.println(&quot;Approximate object size in bytes &quot; + data.length);\n</code></pre>\n'}, {'answer_id': 71683336, 'author': 'granadaCoder', 'author_id': 214977, 'author_profile': 'https://Stackoverflow.com/users/214977', 'pm_score': 2, 'selected': False, 'text': '<p>A possible year 2022 answer.</p>\n<p><a href="https://github.com/ehcache/sizeof" rel="nofollow noreferrer">https://github.com/ehcache/sizeof</a></p>\n<p><a href="https://mvnrepository.com/artifact/org.ehcache/sizeof" rel="nofollow noreferrer">https://mvnrepository.com/artifact/org.ehcache/sizeof</a></p>\n<p><a href="https://mvnrepository.com/artifact/org.ehcache/sizeof/0.4.0" rel="nofollow noreferrer">https://mvnrepository.com/artifact/org.ehcache/sizeof/0.4.0</a></p>\n<p>Version 0.4.0 has only a (compile) dependency on</p>\n<p><a href="https://mvnrepository.com/artifact/org.slf4j/slf4j-api" rel="nofollow noreferrer">https://mvnrepository.com/artifact/org.slf4j/slf4j-api</a></p>\n<p>which is a good thing.</p>\n<p>Sample code:</p>\n<pre><code>//import org.ehcache.sizeof.SizeOf;\n\nSizeOf sizeOf = SizeOf.newInstance(); // (1)\nlong shallowSize = sizeOf.sizeOf(someObject); // (2)\nlong deepSize = sizeOf.deepSizeOf(someObject); // (3)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/52353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5074/']