1

My experience is that Java requires about twice as much RAM compared to C (comparing char arrays or other comparisons). I also read in a hardware book that Java takes about twice RAM than C. Is is based solely on empirical evidence or also has a theoretical explanation? Is there a theoretical limit that limits Java from minimizing its memory usage?

  • Have you considered comparing C arrays to C++ vectors (or Java arrays to C++ vectors) and similar objects in the them? Are you comparing [] arrays? or ArrayList() arrays? What types of objects do you have in them? How do you produce the results of the memory usage? – user40980 Jun 8 '14 at 0:23
  • 4
    1st thing: char in java is 2 bytes while in most C implementations char is 1 byte – ratchet freak Jun 8 '14 at 0:23
  • 4
    In garbage collected languages (like Java), memory that you don't use anymore tends to hang around longer than in languages with manual memory management (like C). This means that the overall memory footprint of an application will also get larger. How much depends on how often the collector runs. – Bart van Ingen Schenau Jun 8 '14 at 5:29
4

Typically they don't (I know, I know) as an array of primitive types are allocated in the same way as C arrays - contiguous blocks of memory for each item. However, an array of objects is a bit different as you get an array of pointers that reference the java objects. C would allocate a contiguous block of memory to hold the actual objects.

A char in Java is 2 bytes though, maybe this is what you're noticing (or if you end up with wrappered types - a char that is retrieved from a JDK method might require wrapping in which case it takes up 16 bytes), or maybe you're noticing that Java arrays take up 12 bytes just to get started, and then are rounded off to the nearest memory alignment block (ie 8 bytes)

See an overview of memory saving techniques in Java.

16 bytes per char in Java if you're not very careful.. ouch.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.