javamemorytypesfinal

Do datatypes influence how much memory is used? Does the final keyword change it?


I don't know much about how memory actually works, but I wanted to know if storing the number 28 (5 bits) takes up different amounts of memory when it's stored as an int, long, short or byte? Does the final keyword limit the memory usage to only the number of bits required?

I couldn't think of a way to test this nor did I find anything about this online.


Solution

  • Limiting the datatype may indeed limit the space needed to store it. But your example of 5 bits will still occupy at least 8 bits in memory, it will be rounded up.

    As a variable (constant or not) in an object, it will probably be zero padded so that each property starts on an even "word" address. A word is the preferred integer size, typically 64 bits on a desktop computer or smaller for embedded or iot devices. So 5 properties of 1 byte each will occupy 5x64 bits on a 64 bit computer.

    But an array of bytes (byte = 8 bits) will however only allocate one byte per element (and possibly zero pad at the end of the entire array to become an even word size), so here it will definitely matter when it comes to storage size.

    constants (static final) will occupy less space because they are only stored once in metaspace, the static class memory. As you instantiate new objects of your class, constant values are not copied to the object space on the heap. Instead, each time the value is read, it's just read from the class definition in metaspace.

    When it comes to performance, an array of bytes will also occupy less space in caches (more data will fit) and that will increase performance. If you are working with a GPU, or the CPU (and compiler) supports SIMD instructions, you can gain a lot of performance using 8, 16 or 32 bits integers on a 64-bit computer.

    Small constants, like 2147483000 (31 bits), can actually work a bit if luck outperform a bigger number like 8589934000 (33 bits)! But this is not something that you should define your program architecture at all, but seen more as fun fact. 🙂 Reason for the possible extra performance is that in can be embedded directly as a constant in some assembler instructions. The entire instruction must fit in 64 bits. This includes the actual instruction, the result register, and the constant. Example LDR rd, =const. The const will not fit if its 64 bits, but a 31 bit const will!