Memory Usage – Analyzing Memory Usage in Java vs C++

algorithmscdata structuresjavamemory

How does the memory usage of an integer object written in Java compare\contrast with the memory usage of a integer object written in C++? Is the difference negligible? No difference? A big difference? I'm guessing it's the same because an int is an int regardless of the language (?)

The reason why I asked this is because I was reading about the importance of knowing when a program's memory requirements will prevent the programmer from solving a given problem.

What fascinated me is the amount of memory required for creating a single Java object. Take for example, an integer object. Correct me if I'm wrong but a Java integer object requires 24 bytes of memory:

  • 4 bytes for its int instance variable
  • 16 bytes of overhead (reference to the object's class, garbage collection info & synchronization info)
  • 4 bytes of padding

As another example, a Java array (which is implemented as an object) requires 48+bytes:

  • 24 bytes of header info
  • 16 bytes of object overhead
  • 4 bytes for length
  • 4 bytes for padding
  • plus the memory needed to store the values

How do these memory usages compare with the same code written in C++?

I used to be oblivious about the memory usage of the C++ and Java programs I wrote, but now that I'm beginning to learn about algorithms, I'm having a greater appreciation for the computer's resources.

Best Answer

It depends on the platform and implementation.

C++ guarantees that the size of char is exactly one byte and at least 8 bits wide. Then, size of a short int is at least 16 bits and not smaller than char. Size of an int is at least as big as size of short int. Size of long int is at least 32 bits and not smaller than int.

sizeof(char) == 1; sizeof(long int) >= sizeof(int) >= sizeof(short int) >= sizeof(bool) >= sizeof(char).

The actual memory model of C++ is very compact and predictable though. For example there is no metadata in objects, arrays or pointers. Structures and classes are contiguous just like arrays are, but padding may be placed where necessary and needed.

Frankly though, such comparison is silly at best as the Java memory usage depends more on the Java implementation than on the code it runs.

Related Topic