31

I was reading the comments on this answer and I saw this quote.

Object instantiation and object-oriented features are blazing fast to use (faster than C++ in many cases) because they're designed in from the beginning. and Collections are fast. Standard Java beats standard C/C++ in this area, even for most optimized C code.

One user (with really high rep I might add) boldly defended this claim, stating that

  1. heap allocation in java is better than C++'s

  2. and added this statement defending the collections in java

    And Java collections are fast compared to C++ collections due largely to the different memory subsystem.

So my question is can any of this really be true, and if so why is java's heap allocation so much faster.

25
  • 26
    Did the user provide any evidence to this claim? I can imagine it would be true in some cases, false in others. Commented Aug 16, 2013 at 7:36
  • 2
    It is pretty hard to beat native code in speed, for some things this might be true Commented Aug 16, 2013 at 7:37
  • 3
    "due to the different memory subsystem" is not "a better put together argument". It doesn't explain anything. He is right about memory allocations, they are typically faster in managed languages, because they're effectively implemented as a single stack push operation, moving a single pointer (at the cost of having occasional GC pauses). But the "collections are faster because handwaving" one is nonsense Commented Aug 16, 2013 at 7:41
  • 3
    @aaronman SO doesn't remove answers for being incorrect; it relies on the community to downvote or comment on incorrect answers. Unfortunately, misinformation, especially on hot topics like Java vs C++, spreads wildly. With a topic like that, people will upvote/accept/defend the answer they want to believe. The best you can do is keep your own personal information filter in good working condition. The highest voted answer on this very question, for example, is the one with the least backed claims and most unrealistic view (the true answer, like others have stated, is: it depends). Commented Aug 16, 2013 at 8:42
  • 8
    Sigh. Java is the only language with a marketing department, and they work overtime trashing C++. Fifteen years ago, just about every article about Java started with a cheap shot at C++ (my favorite was the assertion that C++ couldn't have garbage collection because it didn't run in a virtual machine; so many things wrong there that you just shake your head in despair); you had to read the second paragraph to find out what the article was about. Commented Aug 16, 2013 at 12:09

5 Answers 5

45

This sort of statement is ridiculous; people making it are either incredibly uninformed, or incredibly dishonest. In particular:

  • The speed of dynamic memory allocation in the two cases will depend on the pattern of dynamic memory use, as well as the implementation. It is trivial for someone familiar with the algorithms used in both cases to write a benchmark proving which ever one he wanted to be faster. (Thus, for example, programs using large, complex graphs that are build, then torn down and rebuilt, will typically run faster under garbage collection. As will programs that never use enough dynamic memory to trigger the collector. Programs using few, large, long lived allocations will often run faster with manual memory management.)

  • When comparing the collections, you have to consider what is in the collections. If you're comparing large vectors of double, for example, the difference between Java and C++ will likely be slight, and could go either way. If you're comparing large vectors of Point, where Point is a value class containing two doubles, C++ will probably blow Java out of the water, because it uses pure value semantics (with no additional dynamic allocation), where as Java needs to dynamically allocate each Point (and no dynamic allocation is always faster than even the fastest dynamic allocation). If the Point class in Java is correctly designed to act as a value (and thus immutable, like java.lang.String), then doing a translation on the Point in a vector will require a new allocation for every Point; in C++, you could just assign.

  • Much depends on the optimizer. In Java, the optimizer works with perfect knowledge of the actual use cases, in this particular run of the program, and perfect knowledge of the actual processor it is running on, in this run. In C++, the optimizer must work with data from a profiling run, which will never correspond exactly to any one run of the program, and the optimizer must (usually) generate code that will run (and run quickly) on a wide variety of processor versions. On the other hand, the C++ optimizer may take significantly more time analysing the different paths (and effective optimization can require a lot of CPU); the Java optimizer has to be fairly quick.

  • Finally, although not relevant to all applications, C++ can be single threaded. In which case, no locking is needed in the allocator, which is never the case in Java.

With regards to the two numbered points: C++ can use more or less the same algorithms as Java in its heap allocator. I've used C++ programs where the ::operator delete() function was empty, and the memory was garbage collected. (If your application allocates lots of short lived, small objects, such an allocator will probably speed things up.) And as for the second: the really big advantage C++ has is that its memory model doesn't require everything to be dynamically allocated. Even if allocation in Java takes only a tenth of the time it would take in C++ (which could be the case, if you only count the allocation, and not the time needed for the collector sweeps), with large vectors of Point, as above, you're comparing two or three allocations in C++ with millions of allocations in Java.

And finally: "why is Java's heap allocation so much faster?" It isn't, necessarily, if you amortise the time for the collection phases. The time for the allocation itself can be very cheap, because Java (or at least most Java implementations) use a relocating collector, which results in all of the free memory being in a single contiguous block. This is at least partially offset by the time needed in the collector: to get that contiguity, you've got to move data, which means a lot of copying. In most implementations, it also means an additional indirection in the pointers, and a lot of special logic to avoid issues when one thread has the address in a register, or such.

Sign up to request clarification or add additional context in comments.

7 Comments

The JVM spec does not require the existence of a JIT compiler; even though it's very common these days. Similarly, C++ does not prohibit the existence of a JIT compiler, although as far as I know none exists. Also, to clarify, the optimizer time comparison you mentioned is one-time at compile-time for C++ (assuming static compilation) and run-time for Java (assuming JIT) -- it's not a direct comparison, and leaves out the initial Java compilation step (which is more analogous to the C++ case) as well.
@JasonC The distinction one-time vs recurring cost for the optimization is subsumed in the fact that "the C++ optimizer can take significantly more time". (Although I believe that there have been JVM which cached the results of JIT. In which case, optimization could be a one-time cost there as well.)
I suppose it is significant to consider whose time it takes when weighing two languages against each other. One-time initial compilation is developer time, run-time delays are user time; in most cases the goal is to minimize the latter, but in any case the user, at least, is fairly unaware of the developer, and the two are separate beasts.
@JasonC That is, again, subsumed in the comment about the time available. It's not just developer vs user: there's the fact that the C++ optimizer runs long before you actually use the program, or need its output, which allows it to take far more time.
@JasonC The first. The correct word, back when I was learning English, would have been "may", but I've fallen into the widespread habit of using "can" when it should be "may".
|
30

Your questions don't have concrete answers. For example, C++ does not define memory management at all. It leaves allocation details up to the library implementation. Therefore, within the bounds of C++, a given platform may have a very slow heap allocation scheme, and Java would certainly be faster if it bypasses that. On another platform, memory allocations may be blazing fast, outperforming Java. As James Kanze pointed out, Java also places very little constraints on memory management (e.g. even the GC algorithm is entirely up to the JVM implementor). Because Java and C++ do not place constraints on memory management, there is no concrete answer to that question. C++ is purposefully open about underlying hardware and kernel functions, and Java is purposefully open about JVM memory management. So the question becomes very fuzzy.

You may find that some operations are faster in Java, and some not. You never know until you try, however:

In practice, the real differences lie in your higher level algorithms and implementations. For all but the most absolutely performance critical applications, the differences in performance of identical data structures in different languages is completely negligible compared to the performance characteristics of the algorithm itself. Concentrate on optimizing your higher level implementations. Only after you have done so, and after you have determined that your performance requirements are not being met, and after you have benchmarked and found (unlikely) that your bottleneck is in container implementations, should you start to think of things like this.

In general, as soon as you find yourself thinking or reading about C++ vs. Java issues, stop and refocus on something productive.

13 Comments

Except I'm not designing a performance critical application, I'm just curious
Just to help you with giving an answer, I'm not deciding between the two langs (big C++ fan), I just want to know why these statements are or aren't true
Try it! Performance will vary based on many different things; looking at the memory models alone is not enough to determine if one is "faster" than the other. Your data access patterns can also affect performance, things like caching, spanning page boundaries, alignment issues, and other low level characteristics can make it extremely difficult to compare these kinds of things without context. You can tweak Java GC parameters to tune them to your applications needs, that's another potential outside force in determining performance.
ehh your points are valid I just don't like ur answer, I'm just happy I basically asked the question is java faster than c++ and got away with it
@JasonC Both C++ and Java partially specify a number of constraints on the memory model, while leaving a number of details up to the implementation. And while the constraints are very different, I don't think that one is any more constraining than the other.
|
16

Java heap is faster because (simplified) all you need to do to allocate is to increase heap top pointer (just like on stack). It is possible because heap is periodically compacted. So your price for speed is:

  1. Periodic GC pauses for heap compacting
  2. Increased memory usage

There is no free cheese... So while collection operations may be fast, it is amortized by overall slowing down during GC work.

9 Comments

But to answer the other half, are java collections actually faster because of that?
All you need to do to allocate.
Prolly gonna accept ur answer but I'll wait till tmrw, maybe I'll realize that I was insane for even asking this question
@aaronman There could also cache behaviour considerations which could matter in some domains. Naively, one would expect an array of java objects to have worse behaviour due to non-locality, in a similar way to how a vector<T*> could have worse behaviour than a vector<T>.
Jason C's answer is much more complete. This answer makes the assumptions that 1) Java has a defined memory model, and 2) C++ has a defined memory model. Neither assumption is correct (the memory model for both is left to the implementation - and will differ with different JVMs or libraries, respectively). Additionally, it isn't a fair comparison because you'd be comparing the allocation+usage model (Java) to allocation+usage+deallocation model (C++). For a true comparison, you would have to include the GC's time to clean up the memory.
|
12

While I am a fan of Java, it is worth noting that C++ supports allocation of objects on the stack which is faster than heap allocation.

If you use C++ efficiently with all it various ways of doing the same thing, it will be faster than Java (even if it takes you longer to find that optimal combination)

If you program in C++ as you would in Java, e.g. everything on the heap, all methods virtual, have lots of runtime checks which don't do anything and can be optimised away dynamically, it will be slower. Java has optimised these things further as these a) are the only thing Java does, b) can be optimised dynamically more efficiently, c) Java has less features and side effects so it is easier for optimiser for get decent speeds.

10 Comments

if you only use primitives everything in java will be on the stack
Adding to this: All STL containers let you supply a custom allocator, so if you wanted, you could supply an allocator based on e.g. alloca() to keep everything on the stack, or you could preallocate a block on the heap and supply a custom allocator with your own memory model.
@aaronman True, primitive and references are on the stack. In theory Java can place objects on the stack as well, but in practice this rarely works. In future escape analysis may solve this properly.
@PeterLawrey Excellent point. Also, it's worth noting that C++ doesn't actually define a memory model, the details are left to the implementors; so conceivably one platform could have terrible heap allocation performance, another could be blazing fast, another could be optimized for concurrent access, etc. This renders questions about C++ vs. Java memory model performance very difficult to answer -- a more concrete question is "C++ on platform X with runtime implementation Y vs. Java".
Trust me, wasn't planning to
|
1

and Collections are fast. Standard Java beats standard C/C++ in this area, even for most optimized C code.

This may be true for particular collections, but most certainly isn't true for all collections in all usage patterns.

For instance, a java.util.HashMap will outperform a std:map, because the latter is required to be sorted. That is, the fastest Map in the Java Standard Library is faster that the fastest Map in the C++ one (at least prior to C++11, which added the std:unordered_map)

On the other side, a std:Vector<int> is far more efficient that an java.util.ArrayList<Integer> (due to type erasure, you can't use a java.util.ArrayList<int>, and therefore end up with about 4 times the memory consumption, and possibly poorer cache locality, and correspondingly slower iteration).

In short, like most sweeping generalizations, this one doesn't always apply. However, neither would the opposite assertion (that Java is always slower than C++). It really depends on the details, such as how you use the collection, or even which versions of the languages you compare).

3 Comments

Good answer but its silly to compare std::map and hashmap, because they are different data structures, map is generally represented by a red black tree
The quote in the questions compares "Java Collections" with "C++ collections". I read this to mean the collection implementations from the respective standard library. Not my fault that the C++ standard library uses inferior data structures ;-)
As you already know c++11 has unordered_map, and it is an unfair comparison because log n is slower than constant time in any language

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.