I am sure of the opposite, there's no way Java can beat C++ templates at producing efficient code. Give an example. It may approach it, with a particularly smart compiler, but it's always starting from the disadvantageous position. The C++ std::sort() beats C's std::qsort() in the usual cases for the same reason |
C++ templates are known for code-bloat and wasting code cache. It is a double-edge sword. Little templated code = great performance. Too much templated code = poor performance, huge executables and long compile times. You have to be a very advanced programmer to write both fast and readable templated code. Put some sharedptrs here and there, and all your top-performance is gone.
Java theoretically is able to do the same optimisations as C++ templates (= code specialization and call site code inlining), except it can be smarter about not blowing out the L1 cache, because it can specialize just the hotspots (usually loops), not the whole classes / functions. Currently, it is not implemented fully, though. These optimisations will be fully supported probably at some time in Java 7 or Java 8, as part of invokedynamic feature [1]; I don't know if they finished doing them yet. Anyway, currently, even on Java 6, the Collections.sort works just as fast as C++ std::sort (within a 5% measurement error margin), and 10x faster than C's qsort. So wrong example.
But let's modify the example slightly. Put the sort comparison function in a
dynamically loaded module. Now all your performance advantage of templates breaks apart. Java perfectly inlines such call, even if it is virtual and accross module boundary. C++ doesn't. C++ is good for monolithic software. But where modularity comes into play (e.g. dynamically loaded extensions or plugins) or heavy OOP with lots of inheritance and virtual calls, it stands no chance.
Anyway, templates are usually a means of code optimisation, because most programmers can't use them. Most programmers by "readable code" uderstands pure OOP code, using virtual calls, and no templates (except maybe using standard STL containers and std::string). Google and Mozilla forbid most of STL and Boost for stability and performance reasons. So let's do another excercise: write that sort method using pure OOP (just like in Java) and your sorting performance drops even below that of C's qsort.
So to conclude: Java optimizes pure OOP code better than C++. On the other hand C++ templates are (currently) optimised heavier than what Java can do and sometimes, to some degree, they can still deliver performance advantage over pure OOP equivalent. But most of programmers have no problems writing pure OOP code, while only very few can grasp templates and use them *efficiently*.
[1]
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CBwQFjAA&url=http%3A%2F%2Fwww.wiki.jvmlangsummit.com%2Fimages%2F3%2F3e%2F2011_Nutter.pdf&ei=C1EIT7qTHo7QsgbKkbiBDw&usg=AFQjCNFa0gKkdkFGq9I5pkQwO_kiP1X6hQ&sig2=TtuzKeaW1RAw8nG0f6iX0A