Java collections faster than c++ containers?

后端 未结 5 871
鱼传尺愫
鱼传尺愫 2021-01-31 09:07

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

5条回答
  •  醉梦人生
    2021-01-31 09:46

    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 is far more efficient that an java.util.ArrayList (due to type erasure, you can't use a java.util.ArrayList, 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).

提交回复
热议问题