1. Overview

Application size is crucial for start-up time and memory usage, both of which impact performance. Even with today’s powerful hardware, we can significantly reduce an application’s memory footprint through careful coding practices and optimized technical decisions.

The choice of data types, data structures, and class design affects the size of an application. Selecting the most appropriate data types can reduce the cost of running an application in production.

In this tutorial, we’ll learn how to manually estimate the memory size of a Java application, explore various techniques to reduce the memory footprint and use the Java Object Layout (JOL) library to verify our estimations. Finally, because JVMs can have different memory layouts for objects, we’ll use Hotspot JVM. It’s the default JVM in OpenJDK.

2. Maven Dependency

First, let’s add the JOL library to the pom.xml:

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.17</version>
</dependency>

This library provides classes for analyzing and reporting the memory layout of Java objects. Notably, computing the memory footprint depends on the JVM architecture. Different JVMs may have different object memory layouts.

3. Size of Java Primitives and Objects

The RAM of a system is structured like a table with rows and columns. Each data type occupies a specific number of bits used to estimate memory usage. Java primitive types and objects have different memory representations.

3.1. Memory Word

The memory word represents the amount of data a processor can transfer in a single operation. Based on the system architecture, the memory word size is 4 bytes for a 32-bit system and 8 bytes for a 64-bit system.

When a data type can’t fill the minimal size, it’s rounded up to 4 bytes in a 32-bit system and 8 bytes in a 64-bit system, meaning objects are padded to fit these boundaries.

Understanding this gives us in-depth insight into our program memory usage.

3.2. The Size of an Object

An empty class in Java without any fields contains only metadata. This metadata includes:

  • Mark Word: 8 bytes on a 64-bit system
  • Class Pointer: 4 bytes with compressed oops on 64-bit systems

Thus, the minimum size of an object is 16 bytes with memory alignment on a 64-bit system.

3.3. The Size of Primitive Wrappers

Furthermore, primitive wrappers are objects that encapsulate the primitive types. They consist of an object header, a class pointer, and a primitive field.

Here’s an estimation of their size with the memory padding in a 64 bit-system:

Type

Mark Word

Class Pointer

Primitive Value

Memory Padding

Total

Byte

8

4

1

3

16

Short

8

4

1

3

16

Characters

8

4

1

3

16

Integer

8

4

4

16

Float

8

4

4

16

Long

8

4

8

4

24

Double

8

4

8

4

24

In the table above, we define the memory size of wrappers by analyzing the components that contribute to their total size.

4. Example Setup

Now that we know how to estimate the memory size of different Java primitives and objects, let’s set up a simple project and estimate its initial size. First, let’s create a class named Dinosaur:

class Dinosaur {
    Integer id;
    Integer age;
    String feedingHabits;
    DinosaurType type;
    String habitat;
    Boolean isExtinct;
    Boolean isCarnivorous;
    Boolean isHerbivorous;
    Boolean isOmnivorous;

    // constructor
}

Next, let’s define a class that represents the Dinosaur taxonomy:

class DinosaurType {
    String kingdom;
    String phylum;
    String clazz;
    String order;
    String family;
    String genus;
    String species;

    // constructor
}

Here, we create a class named DinosaurType that is referenced in the Dinosaur class.

5. Estimating Initial Memory Size

Let’s compute the initial memory size of our application without any optimization yet. First, let’s instantiate the Dinosaur class:

DinosaurType dinosaurType 
  = new DinosaurType("Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");
Dinosaur dinosaur = new Dinosaur(1, 10, "Carnivorous", dinosaurType, "Land", true, false, false, true);

Then, let’s use the JOL library to estimate the size of a dinosaur object:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Estimating the size without optimization gives us 624 bytes. Notably, this could vary based on JVM implementation.

6. Optimizing Initial Memory Size

Now that we have an understanding of the initial memory footprint, let’s explore how we can optimize it.

6.1. Using Primitive Types

Let’s revisit the Dinosaur class and replace primitive wrappers with primitive equivalents:

class Dinosaur {
    int id;
    int age;
    String feedingHabits;
    DinosaurType type;
    String habitat;
    boolean isExtinct;
    boolean isCarnivorous;
    boolean isHerbivorous;
    boolean isOmnivorous;
    // constructor
}

In the code above, we change the types of id, age, isExtinct, isCarnivorous, and other wrappers to use primitive types instead. This action saves us some bytes. Next, let’s estimate the memory size:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Here’s the log output:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 552

The new size is 552 bytes compared to the initial 624 bytes. Therefore, using primitive types instead of wrappers saves us 72 bytes.

Furthermore, we can use a short type for Dinosaur age. A short in Java can store up to 32767 whole numbers:

// ...
short age;
// ...

Next, let’s see the console output after using short type for age:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 552

From the console output, the memory size is still 552 bytes — no difference in this case. However, we can always use the most narrow type possible for memory efficiency.

In the case of fields like feedingHabits, habitat, and taxonomy information, we retain the String type due to its flexibility. Alternatives like char[] lack the functionality that String provides, such as built-in methods for manipulating text.

To further reduce our memory footprint, we can merge the fields in related classes, consolidating them into a single class. Let’s merge the Dinosaur and DinosaurType classes into a single class:

class DinosaurNew {
    int id;
    short age;
    String feedingHabits;
    String habitat;
    boolean isExtinct;
    boolean isCarnivorous;
    boolean isHerbivorous;
    boolean isOmnivorous;
    String kingdom;
    String phylum;
    String clazz;
    String order;
    String family;
    String genus;
    String species;
    // constructor
}

Here, we create a new class by merging the two initial classes’ fields. This is beneficial since Dinosaur instances have unique taxonomy. Assuming Dinosaur instances share the same taxonomy, this won’t be an efficient approach. It’s crucial to analyze the use case before merging classes.

Next, let’s instantiate the new class:

DinosaurNew dinosaurNew
  = new DinosaurNew(1, (short) 10, "Carnivorous", "Land", true, false, false, true, "Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");

Then, let’s compute the memory size:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

Here’s the console output:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 536

By merging the Dinosaur and DinosaurType classes, we save 16 bytes that would otherwise be used for the object’s mark word, class pointer, and memory padding.

6.3. Bit Packing for Boolean Fields

In a case where we have multiple boolean fields, we can pack them into a single short type. First, let’s define the bit positions:

static final short IS_EXTINCT = 0, IS_CARNIVOROUS = 1, IS_HERBIVOROUS = 2, IS_OMNIVOROUS = 3;

Next, let’s write a method to convert the booleans to short:

static short convertToShort(
  boolean isExtinct, boolean isCarnivorous, boolean isHerbivorous, boolean isOmnivorous) {
    short result = 0;
    result |= (short) (isExtinct ? 1 << IS_EXTINCT : 0);
    result |= (short) (isCarnivorous ? 1 << IS_CARNIVOROUS : 0);
    result |= (short) (isHerbivorous ? 1 << IS_HERBIVOROUS : 0);
    result |= (short) (isOmnivorous ? 1 << IS_OMNIVOROUS : 0);
    return result;
}

The method above takes four boolean parameters and converts them to a single short value where each bit represents a boolean. If the boolean value is true, it shifts 1 to the left by the position of that flag. If the boolean is false, it uses zero with no bits set. Finally, we use the bitwise OR operator to combine all these values.

Also, let’s write a method to convert back to boolean:

static boolean convertToBoolean(short value, short flagPosition) {
    return (value >> flagPosition & 1) == 1;
}

The method above extracts a single boolean value from the packed short.

Next, let’s remove the four boolean fields and replace them with a single short flag:

short flag;

Finally, let’s instantiate the Dinosaur object and compute the memory footprint:

short flags = DinousaurBitPacking.convertToShort(true, false, false, true);
DinousaurBitPacking dinosaur 
  = new DinousaurBitPacking(1, (short) 10, "Carnivorous", "Land", flags, "Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");
 
LOGGER.info("{} {} {} {}", 
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_EXTINCT),
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_CARNIVOROUS),
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_HERBIVOROUS), 
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_OMNIVOROUS));
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Now, we have a single short value to represent the four boolean values. Here’s the JOL computation:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- true false false true
[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 528

We’re now down to 528 bytes from 536 bytes.

7. Java Collections

Java Collections have complex internal structures, and computing this structure manually might be tedious. However, we can use the Eclipse Collection library for additional memory optimization.

7.1. Standard Java Collections

Let’s compute the memory footprint of an ArrayList of Dinosaur type:

List<DinosaurNew> dinosaurNew = new ArrayList<>();
dinosaurPrimitives.add(dinosaurNew);
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

The code above outputs 616 bytes to the console.

7.2. Eclipse Collection

Now, let’s use the Eclipse Collection library to reduce the memory footprint:

MutableList<DinosaurNew> dinosaurPrimitivesList = FastList.newListWith(dinosaurNew);
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

In the code above, we create a collection of MutableList of Dinosaur using the third-party collection library, which outputs 584 bytes to the console. This means that there’s a 32-byte difference between the standard and Eclipse collections libraries.

7.3. Primitive Collections

Also, the Eclipse Collection provides collections of primitive types. These primitive collections avoid the overhead cost of wrapper classes, leading to substantial memory savings.

Furthermore, libraries like Trove, Fastutil, and Colt provide primitive collections. Also, these third-party libraries are performance-efficient compared to the Java standard collections.

8. Conclusion

In this article, we learned how to estimate the memory size of Java primitives and objects. Also, we estimated the initial memory footprint of an application and then used approaches such as using primitives instead of wrappers, combining classes for related objects, and using narrow types like short to reduce the memory footprint.

As always, the complete example code is available over on GitHub.