Analyzing Memory Usage: Java vs C++ Negligible?

Posted by Anthony on Programmers See other posts from Programmers or by Anthony
Published on 2012-08-18T10:19:51Z Indexed on 2012/09/10 15:49 UTC
Read the original article Hit count: 303

Filed under:
|
|
|
|

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.

© Programmers or respective owner

Related posts about java

Related posts about c++