Which will take up more memory, int or Integer?

In Java, both int and Integer are used to represent integer type data, but there are some important differences between them, including memory footprint. Briefly:

1. Int is Java's primitive data type (primitive type), which directly stores integer values. In a 32-bit system, an int occupies 4 bytes (32 bits), and in a 64-bit system, an int also occupies 4 bytes.

2. Integer is one of Java's wrapper classes (wrapper class), which provides a way to convert int to object. Integer objects contain an int field and associated methods. On 32-bit systems and 64-bit systems, an Integer object will occupy at least 16 bytes (128 bits), which includes the header overhead of the object, the storage of the int field, and other object management overhead.

To sum up, from the perspective of memory usage, int occupies much less memory than Integer.

Next, let's look at a specific code demonstration to show the memory usage of int and Integer:

public class MemoryUsageDemo {
    
    
    public static void main(String[] args) {
    
    
        int primitiveInt = 42;
        Integer integerObject = 42;

        long primitiveIntSize = MemoryUtil.sizeOf(primitiveInt);
        long integerObjectSize = MemoryUtil.sizeOf(integerObject);

        System.out.println("int size: " + primitiveIntSize + " bytes");
        System.out.println("Integer size: " + integerObjectSize + " bytes");
    }
}

Please note that the above code uses the third-party library MemoryUtil to measure the size of the object. We need to use tools like Java Object Layout (JOL) to measure the memory usage of objects. In the example, the int should be 4 bytes in size and the Integer should be larger than 4 bytes because it is an object and also contains some additional overhead.

Summary: From the perspective of memory usage, int takes up less memory because it is a primitive data type, while Integer is an object and requires additional overhead. However, in some cases, we still use Integer objects, such as ints that need to be converted to objects for storage in collection classes.

Guess you like

Origin blog.csdn.net/cz_00001/article/details/132500623