What is the memory consumption of an object in Java?

Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?

How much memory is allocated for an object?
How much additional space is used when adding an attribute?

Asked by: Oliver398 | Posted: 21-01-2022

Answer 1

Mindprod points out that this is not a straightforward question to answer:

A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
For example, the JVM or native compiler might decide to store a boolean[] in 64-bit long chunks like a BitSet. It does not have to tell you, so long as the program gives the same answers.

  • It might allocate some temporary Objects on the stack.
  • It may optimize some variables or method calls totally out of existence replacing them with constants.
  • It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.

Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.

Measurement methods

You can use Instrumentation.getObjectSize() to obtain an estimate of the storage consumed by an object.

To visualize the actual object layout, footprint, and references, you can use the JOL (Java Object Layout) tool.

Object headers and Object references

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)

Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to -Xmx32G; and 8 bytes above 32Gb (-Xmx32G). (See compressed object references.)

As a result, a 64-bit JVM would typically require 30-50% more heap space. (Should I use a 32- or a 64-bit JVM?, 2012, JDK 1.7)

Boxed types, arrays, and strings

Boxed wrappers have overhead compared to primitive types (from JavaWorld):

  • Integer: The 16-byte result is a little worse than I expected because an int value can fit into just 4 extra bytes. Using an Integer costs me a 300 percent memory overhead compared to when I can store the value as a primitive type

  • Long: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a Long is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, Integer had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.

Other containers are costly too:

  • Multidimensional arrays: it offers another surprise.
    Developers commonly employ constructs like int[dim1][dim2] in numerical and scientific computing.

    In an int[dim1][dim2] array instance, every nested int[dim2] array is an Object in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.

    For example, a int[128][2] instance takes 3,600 bytes. Compared to the 1,040 bytes an int[256] instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of byte[256][1], the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.

  • String: a String's memory growth tracks its internal char array's growth. However, the String class adds another 24 bytes of overhead.

    For a nonempty String of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.


Consider this example object:

class X {                      // 8 bytes for reference to the class definition
   int a;                      // 4 bytes
   byte b;                     // 1 byte
   Integer c = new Integer();  // 4 bytes for a reference

A naïve sum would suggest that an instance of X would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.

Answered by: David881 | Posted: 22-02-2022

Answer 2

It depends on architecture/jdk. For a modern JDK and 64bit architecture, an object has 12-bytes header and padding by 8 bytes - so minimum object size is 16 bytes. You can use a tool called Java Object Layout to determine a size and get details about object layout and internal structure of any entity or guess this information by class reference. Example of an output for Integer on my environment:

Running 64-bit HotSpot VM.
Using compressed oop with 3-bit shift.
Using compressed klass with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

java.lang.Integer object internals:
      0    12       (object header)                N/A
     12     4   int Integer.value                  N/A
Instance size: 16 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

So, for Integer, instance size is 16 bytes, because 4-bytes int compacted in place right after header and before padding boundary.

Code sample:

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.util.VMSupport;

public static void main(String[] args) {

If you use maven, to get JOL:


Answered by: David937 | Posted: 22-02-2022

Answer 3

Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as shown in another answer, at least some JVMs will pack fairly tightly. Consider a class like this:

public class SingleByte
    private byte b;


public class OneHundredBytes
    private byte b00, b01, ..., b99;

On a 32-bit JVM, I'd expect 100 instances of SingleByte to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of OneHundredBytes to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in OneHundredBytes, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).

EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of SingleByte would take 16 bytes.

Either way, the "single large object" will be at least as efficient as multiple small objects - for simple cases like this.

Answered by: Roland678 | Posted: 22-02-2022

Answer 4

It appears that every object has an overhead of 16 bytes on 32-bit systems (and 24-byte on 64-bit systems).

http://algs4.cs.princeton.edu/14analysis/ is a good source of information. One example among many good ones is the following.

enter image description here

http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf is also very informative, for example:

enter image description here

Answered by: Marcus562 | Posted: 22-02-2022

Answer 5

The total used / free memory of a program can be obtained in the program via


The runtime has several methods which relate to the memory. The following coding example demonstrates its usage.

 public class PerformanceTest {
     private static final long MEGABYTE = 1024L * 1024L;

     public static long bytesToMegabytes(long bytes) {
         return bytes / MEGABYTE;

     public static void main(String[] args) {
         // I assume you will know how to create an object Person yourself...
         List <Person> list = new ArrayList <Person> ();
         for (int i = 0; i <= 100_000; i++) {
             list.add(new Person("Jim", "Knopf"));

         // Get the Java runtime
         Runtime runtime = Runtime.getRuntime();

         // Run the garbage collector

         // Calculate the used memory
         long memory = runtime.totalMemory() - runtime.freeMemory();
         System.out.println("Used memory is bytes: " + memory);
         System.out.println("Used memory is megabytes: " + bytesToMegabytes(memory));

Answered by: Kimberly999 | Posted: 22-02-2022

Answer 6

Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?


How much memory is allocated for an object?

  • The overhead is 8 bytes on 32-bit, 12 bytes on 64-bit; and then rounded up to a multiple of 4 bytes (32-bit) or 8 bytes (64-bit).

How much additional space is used when adding an attribute?

  • Attributes range from 1 byte (byte) to 8 bytes (long/double), but references are either 4 bytes or 8 bytes depending not on whether it's 32bit or 64bit, but rather whether -Xmx is < 32Gb or >= 32Gb: typical 64-bit JVM's have an optimisation called "-UseCompressedOops" which compress references to 4 bytes if the heap is below 32Gb.

Answered by: Adelaide299 | Posted: 22-02-2022

Answer 7

No, registering an object takes a bit of memory too. 100 objects with 1 attribute will take up more memory.

Answered by: Briony724 | Posted: 22-02-2022

Answer 8

The question will be a very broad one.

It depends on the class variable or you may call as states memory usage in java.

It also has some additional memory requirement for headers and referencing.

The heap memory used by a Java object includes

  • memory for primitive fields, according to their size (see below for Sizes of primitive types);

  • memory for reference fields (4 bytes each);

  • an object header, consisting of a few bytes of "housekeeping" information;

Objects in java also requires some "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.

Java object header size varies on 32 and 64 bit jvm.

Although these are the main memory consumers jvm also requires additional fields sometimes like for alignment of the code e.t.c.

Sizes of primitive types

boolean & byte -- 1

char & short -- 2

int & float -- 4

long & double -- 8

Answered by: Kimberly904 | Posted: 22-02-2022

Answer 9

I've gotten very good results from the java.lang.instrument.Instrumentation approach mentioned in another answer. For good examples of its use, see the entry, Instrumentation Memory Counter from the JavaSpecialists' Newsletter and the java.sizeOf library on SourceForge.

Answered by: Carlos161 | Posted: 22-02-2022

Answer 10

In case it's useful to anyone, you can download from my web site a small Java agent for querying the memory usage of an object. It'll let you query "deep" memory usage as well.

Answered by: Vanessa421 | Posted: 22-02-2022

Answer 11

no, 100 small objects needs more information (memory) than one big.

Answered by: Marcus112 | Posted: 22-02-2022

Answer 12

The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).

For the detailed rules for the SUN JVM check my old blog

Regards, Markus

Answered by: Aida113 | Posted: 22-02-2022

Similar questions

unix - Java memory consumption, "top" and HP-Ux

We ship Java applications that are run on Linux, AIX and HP-Ux (PA-RISC). We seem to struggle to get acceptable levels of performance on HP-Ux from applications that work just fine in the other two environments. This is true of both execution time and memory consumption. Although I'm yet to find a definitive article on "why", I believe that measuring memory consumption using "top" is a crude approach due to things ...

shell - time and memory consumption java class and c++ file

Hello I am doing a project on programming algorithm measurements how I can know the time of execution from start to finish and RAM consumption of a class made an algorithm in java and file made in c++. I need to do from the linux shell because the idea is that these results are stored in variables of Ruby on Rails for web viewing. so I can't use any external program unless this gives me the answer in linux ...

java - High memory consumption by an Image

Below is a sample code. Where it loads 6 Images and displays them in a screen. Each Image size is of 2.3 MB. So on loading each Image, I should see a rise of memory consumption of 3 MB approx for each Image loaded. But it turns out that it loads 10 MB for each Image. import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javafx.application.Application; import javafx.geometry...

java - Netty 4 beta1 memory consumption

I noticed an large increase in memory consumption (+70 mo) between Netty 4 Alpha 8 and Netty 4 Beta 1 Tested on Win7 with java 7 runtime. Netty 4 alpha 8 code: https://github.com/ccheneau/Holmes/tree/b_netty_4_alpha_8/holmes-core/src/main/java/net/holmes/core/http Ne...

java - JavaFx and memory consumption

I just made an application with java fx that cycles videos in a folder. I had to set the next video firing the setonendofmedia event, so they are in a cycle, but the problem is that the application loads every video at the beginning, so after a while it fills memory and crashes. Is there another way to cycle videos without pre-load them or a way to flush memory every while? This is my code : packag...

Java - Odd memory consumption between x32 and x64

I've been profiling the x64 version of my application as the memory usage has been outrageously high, all of it seems to be coming from the JavaFX MediaPlayer, i'm correctly releasing listeners and eventhandlers. Here is the stark contrast. The x32 version at start And now the x64 version at start

java - Lower memory consumption with byte arrays

I got alot of byte arrays in my application, which contain often the same value in succession. I need access on this array all the time though, so a compression could lead to problems with performance. My program consumes 1.5GB of memory (Task Manager), of which 1GB is byte arrays only. Is there a way to handle this type of data better? To make clear what im talking about: Im working on an voxel engine, and...

Memory consumption java file stream

I'm reading a file through a java nio interface, directly to a stream. This launches async http requests and handles these in the future. Every 10,000 records, I upload this result to a server and I clear the records, so this clears my memory consumption. I start with the byte array, that stays in the memory constantly. The http client (commons CloseableHttpAsyncClient) fires the requests async, so these a...

Java memory consumption puzzle

I'm very puzzled by a problem I observe in our server application. The server is a CentOS 7 machine with 48 cores and 64GB memory Java is OpenJDK 8 Application Server is WildFly 9 Memory and GC params: -Xss256k -Xmx8192m -XX:+UseG1GC -XX:MaxGCPauseMillis=20 The main use case receives CORBA requests in one java process and delegates them by calling remote ...

Java: JVM memory consumption

I am playing around with Java, parameter -Xms and class Runtime. I see that JVM allocates about 15% of the memory that is available - regardless how much it is. Runtime rt Runtime.getRuntime (); long total = rt.totalMemory () long free = rt.freeMemory (); That is the case if I start my programm with paramter -Xms4000m as well as with

unix - Java memory consumption, "top" and HP-Ux

We ship Java applications that are run on Linux, AIX and HP-Ux (PA-RISC). We seem to struggle to get acceptable levels of performance on HP-Ux from applications that work just fine in the other two environments. This is true of both execution time and memory consumption. Although I'm yet to find a definitive article on "why", I believe that measuring memory consumption using "top" is a crude approach due to things ...

Updating from Java VM 5 to 6 gave a really big increase of memory consumption

I've be working with a Java application run through the command-line. It deals with XML files, specially the dblp.xml database which has more than 400MB. I was using JVM 5 and my app needed sort of 600-700MB of memory to processe the dblp.xml. After updating to JVM 6, it starting needing more than 1gb of memory (something I don't have), although it runs a bit faster. I'm pretty sure of the memory consumpti...

PHP vs. Java are there energy consumption differences?

I heard a rumor, that Java consumes less energy than PHP and was wondering if and how this would be true. I'm currently working in a company where we base most of our apps on PHP. Power consumption has never been the problem for us, but we are working on bigger projects where it might matter. We love PHP for web developing and are wondering how such a rumor can spread and if it is true at all. The example I heard w...

Monitoring memory consumption by different java objects

If we have 300 classes in an application, is it possible to monitor how many instances of each class we have at a given time? Is it possible to know how much memory each instance is consuming? Thanks

java - Classes, Static Methods, or Instance Methods - Memory Consumption and Executable Size in Compiled Languages?

I keep wondering about this to try to improve performance and size of my Flex swfs, how do classes vs. static methods vs. instance methods impact performance and the final compiled "executable's" size? Thinking how it might be possible to apply something like HAML and Sass to Flex... Say I a...

java - How to obtain the consumption memory of running "exe"

I'm developing an "Online Judge System",like SGU "http://acm.sgu.ru/" I wangt to obtain the accurate consumption memory of running ".exe"(.c/.cpp-->.exe) using Java. Process : submit code-->hello.cpp/.c--compile-->hello.exe--run-->results I want to know how to obtain the consumption memory of running "hello.exe" The code:

java - Sun JVM Committed Virtual Memory High Consumption

We have production Tomcat (6.0.18) server which runs with the following settings: -server -Xms7000M -Xmx7000M -Xss128k -XX:+UseFastAccessorMethods -XX:+HeapDumpOnOutOfMemoryError -Dcom.sun.management.jmxremote.port=7009 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Djava.util.logging.manager=org.apache....

Clojure/Java: Most effective method for minimizing bandwidth consumption when performing complex operations on a stream of Amazon S3 data

I'm performing streaming reads of an object using BufferedReader. I need to do two things with this object: Pass it to a SuperCSV csv reader Obtain the raw lines and keep them in a (Clojure) lazy sequence Currently, I am having to use two different BufferedReaders: one as an argument to a SuperCSV CSV reader class and one to initialize the lazy sequence of raw lines. I'm effect...

Java Profiling Tool for CPU consumption

I have used JProfiler, JProbe, AppSight, YourKit for the finding out what code is consuming CPU. But YourKit looks better than others. Is there anything better ?

java - ActiveMQ memory consumption through the roof (page file)... what to do?

We're using an older version of ActiveMQ (5.3.2) (see: Is activemq reliable?) We've removed persistence because we needed more speed. Our worker can keep up with the messages, but, even though the queue typically is at 0 pending, after about 45000 messages processed (a message is typically 100 chars long), the Page file is 8GB!! It doesn...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)