C++ vs Java performance; It’s a tie!

So a while back I came across this Java vs C++ performance benchmark. It was kind of dated and as the Java VM continues to improve (in addition to the C++ compiler I would presume), I thought it would be interesting to rerun the tests to see what we would end up with.

So this is what I did: I started up a new Rackspace Cloud Server of their biggest kind (most CPU and 15.5G RAM) and booted it up with Debian 5.0. I then compiled all the tests and ran them all 25 times each. I used the time utility to measure the elapsed real time used by each test and logged that for later analysis. Of the 25 runs on each test, the slowest and the fastest were removed so that I ended up with 23 sample points pr test. These 23 sample points were then averaged so that we end up with one measure point pr test.


The diagram below shows (click to enlarge) the run time for each of the C++ test cases, compiled with the -O, -O2, and -O3 optimization flags. All test cases are compiled with -march=x86-64, using g++ version 4.3.2.

C++ performance with different optimization flagsNot too surprising, in general, the performance improves with increasing optimizations.


Next up is Java. It’s run with the -client and -server flags, and the diagram below (click to enlarge) shows run time for each Java test case. The Sun Java HotSpot VM, version 1.6.0_20 was used, and as we see there’s not much of a difference between using either the -client or -server flags when benchmarking these test cases.

Java performanceC++ vs Java

So how do they compare to each other? In the diagram below (ones again, click to enlarge), I’ve taken the absolute best run time for each of the tests from both C++ (either -O, -O2, or -O3) and Java (either -client or -server) and set them up against each other.

C++ vs Java performanceAnd the conclusion? It’s a tie between C++ and Java, each “winning” 6 of the 12 test cases.

Additional information

I’ve made available two ZIP files. The first one contains all the source code, compile and run scripts + input files (quite large, therefor the large ZIP size), and the second contains all this + the compiled files and time logs for each of the test cases.

There’s also a Google spreadsheet with all the numbers and diagrams.

Finally, there were two tests I excluded, hash.cpp and hash2.cpp (available in the ZIP files), as the C++ compiler complained and refused to compile the source code due to a deprecated or antiquated header.

75 replies on “C++ vs Java performance; It’s a tie!”

Integrate the area under the curve of the C++ data points vs Java data points to see which has the lessor value (i.e., is in the aggregate the better performing).

Java on several of the test is extraordinarily better than C++. An area under the curve comparison will show Java probably to be substantially better performing than C++.

Rating by the number of test won is really a very misleading way to compare them and is not actually a meaningful comparison at all.

So the test includes JVM start time, code compilation, warming etc…???
if the test took 1h I would say it doesn’t matter… but when the test takes 5 sec…

That is indeed true. The total time measured includes JVM start time etc.

These are all micro benchmarks. If the input size of the input files on the last two tests where smaler, I believe C++ would have performed better than Java.

Benchmarks are useless. You should consider real-world medium/large scale applications with a combination of allocations, I/O and networking. Then you will discover why, statistically speaking, there aren’t widely-used professional applications written in Java.

What kind of BS is that progr?
No widely prof app in Java, which planet have you been living on?

So in doing professional big enterprise stuff for public sector, banks, insurrance etc I see javaEE all over the place and almost no c++. I guess you “statistically speaking” about professional apps include and is limited to desktop such as MS word but then that really dosen’t really quilify as large scale IO as you put as a condition does it..? I think you need to get out and about.

It’s common knowledge among statisticians that 78.45% of all statistics are completely fabricated….. statistically speaking of course!

I think that C++ programmers are much more aware of expensive constructs than Java developers.

And one of the things that I really dislike about Java is their crappy implementation of generics in combination with primitives types, since everything needs to be boxed and unboxed.

Peter Veentjer
Multiverse: Software Transactional Memory for Java

In Scala since version 2.8 it is not the case – generics are specialized for primitive types. I would rather say that what I dislike in C++ is their crappy implementation of generics based on dumb text substitution, with no proper type bounds and variance control. Feels extremely limited in comparison to what Scala generics have to offer.

The HotSpot JVM currently doesn’t have a 64bit client compiler.
Your test is comparing server vs server which is why the results are the same.

Can’t wait to see the next generation of video games and operatings systems written in Java! 😛

You don’t have to wait ….. 🙂
My cable box OS is powered by java.
Even though Android core is C the rest is java (viva Dalvik!).
My SCSI driver for SAN are written in java and only takes 9M of resident memory on CentOS.
Google “java games” and you’ll have a list of those too.
Like I said no need to wait.

In computation, Java is the same as C++. In optimization (algorithms) Java is better than C++. Where C++ wins, is in working with memory. Its possible to make cache-aware programs in C++, while in Java it is impossible. There is no control over allocation in Java. One thing that could improve that (allocating lots of small objects in cache-aware manner, without garbage-collection overhead), would be the introduction a structs, with explicit storage in ByteBuffer-s.


In Java RT (Jsr 1) you have far more control over memory allocation, including doing your own deallocation. Granted, this is a very specific Java version, but it does exist.

My experience (15 years of Java, and now getting back into C/C++ for performance reasons). Some of the algorithms require high-performance, and these are mostly numerical or low-level (system level). A carefully constructed Java program can start in under 4 seconds (native splash screen with GUI on desktop in < 4 seconds). This is acceptable for most users, and certainly for high-end users who are using the software for its functionality and ergonomics.
The additional burden of a JRE download is offset by the robustness of the libraries and cross-platform support. A single bug can ruin your day and turn off customers.

Consider lucene. I can't find anything in C++ that comes close in terms of ease of use, debuggability, performance, licensing, and extensibility/modularity. This statement can be repeated a thousand times with a thousand libraries. Consider Netty. In my benchmarks it was faster than Nginx, the fastest contender. Nginx used less memory, but Netty ran in a constant 1000 connections in C or C++.

This means that any ** complex ** programs involving sockets and complex memory access patterns (i.e., complex object structures possibly requiring synchronized access) will usually be better in Java.

Anything requiring access to low-level resources such as drivers, or high-performance code requiring e.g., optimized matrix libraries you’re better off with C++ (actually, most BLAS routines are still written in FORTRAN). This has to do with the fact that Java still doesn’t take advantage of SSE. It may also have to do with the bytecodes that Java is compiled to, though a compiler expert might be able to address that better than I.

Also, complex but highly structured mathematical programs are probably still better in C++. For example, in Java, each object requires a tiny amount of synchronization data and other housekeeping data that, for millions of tiny objects, makes object orientation almost useless. Hopefully someday the Java community will make the open source version support non-garbage collectable non-synchronizable object support (I think .Net supports something like that).

Finally, the majority of business programms require correctness and ease of modification, often acceptable at a factor 10 slowdown. Java is far easier to modify and change, and verify for correctness.

In my work, I use compiled (native) code for all performance critical and low level requirements, and Java for the rest. This appears to be the ideal architecture if cross-platform support and access to the large base of Java libraries is important to you

Why the argument, just use what gets the job done! It’s this inborn attitude to argue over silly things these days that’s taking this whole world down to it’s knees.

I agree with the several of the above posters: this is a poor comparison. The C++ code is very poorly implemented – no competent engineer would ever nest loops in such a fashion, for instance. A nested loop is going to be removed by the JIT whereas the C++ compiler will honor your request.

Same with method call… you are doing things a C++ engineer would never do, such as dereferencing both the object’s pointer and the vtable n times. That’s silly. As well, you are handling memory management differently in both. Java may not have even deleted its objects yet by this point since the GC may not be called until after the runtime is finished. You explicitly delete (proper practice though maybe should be RAII) instead in C++. On the same mark, the object insertion test is simply absurd.

I’m also going to assume that you are a Java programmer normally as you use Java style in your C++-source.

I didn’t create the code, just re-ran the tests. You’ll find the link if you read the post. Anyway, you are of course free to reimplement the C++ code and rerun the test yourself..

You knuckleheads that keep coming up with these bogus java is better than c/c++ benchmarks clearly don’t know how or aren’t capable of writing an efficient c++ or even more preferably pure ansi c program. The java programs are created a lot of the time with static functions so no object instantiation has to be performed, and the c/c++ functions are clearly not created by someone that knows how to write an efficient c program. The very idea of even trying to come up with a java is better than c program is absurd. Java wouldn’t exist without the c libraries you dummies. It’s not rocket science. It’s simple–java will NEVER be better than C, and even C++ (C++ that’s written CORRECTLY not dummied down by an idiot java software “engineer” that’s right out of college), and by the same token, C++ and even pure highly efficiently written C will never be faster than hand optimized assembler code. How is it you java fan boys still don’t get this is beyond me. It’s a dead language–deal with it. After java is dead, C and C++ and hell even objective C thanks to apple, will still be here. After all, you have to have some efficient language to write the next generation of crap languages for the next generation of bone head “programmers” right? rofl

Java is fantastic. I’m so happy to be programming in Java. Whenever I actually ** need ** integration with something such as a codec or access to native resources, I then write a small amount of C code to access the native resources or a small amount of C code to perform the critical operations, and then interface that with Java using JNI. The result is the best of both worlds.
Java was invented to solve most of the problems with C++, and they largely succeeded.

I actually ** like ** C and assembler (quite a bit, in fact). In some scenarios the effort is justified (codecs, accessing native resources or libraries, performance critical code).
Accessing a database, the network, or writing a GUI in C or C++ does not seem to be justified unless your application a) is not too complex and b) requires a small runtime footprint

I should qualify “small runtime footprint” with “less than 40MB”. Few apps have this requirement (excluding embedded apps).

i think the whole dispute over which .IDE is stupid and pointless. you guys are only fighting over it because each and every one of you guys thinks that the .IDE they are using is better simply because they are using it. i learned pretty quick that its mostly based on preference. and once you learn an .IDE language pretty well, you become familiarized with it to the point where if you try to learn a different ide language you either give up and go back to previous ide, or you tell other people they are dumb cuz they arent using the same ide as you. well stop being so closed minded. just because you dont like a different ide doesnt mean you have to talk crap about the other ones that people use. its like the dispute between people who like rap and people who like rock and roll/metal. they both say the others music is crap just cuz they dont like it. and they wont even try to appreciate the musical art behind both genres. so all of you need to stop acting like close-minded teenagers and stop fighting over something stupid. imagine how much more we could acomplish if we didnt spend all our time fighting over dumb stuff like this. im not saying that you cant have your own opinion, cuz everybody has their own opinion on things. but just stop fighting over it. i mean does it really matter? what does one ide supposedly being better than another have to do with the price of tea in china? nothing at all. everyone of the ides is different, were intended for different purposes. so its all about what your trying to accomplish and preferences. ive read way to many forums where all it is is people arguing back and forth its dumb and i never find any answers about anythin on forums. let forums be for discussions about useful topics, questions, etc.

idk i was really tired, (still am) and fucked up on some pills so i dont even know where have of this came from. lol but if im correct IDE which stands for integrated developing environment. which is what visual studio and visual c, c++ are, java isnt but they are all pretty similar in a lot of ways. idk if i have offended anyone im sorry. i apologize for my lack of self control, and for my unnecessary out burst.

benchmarks are like statistics.
if its faster is it quicker to code, is it more robust, do you have the talent, is speed the key factor.
C++ is used widely in financial mathematics, quants want to code there models to be fast and many have invested time learning it. python is also used – its quick to prototype.
C# is used extensively for GUI’s and can be remarkably reliable (i built an MQ series service on w2k3 that didnt require downtime or reboot in over a year) much to the suprise of the UNIX SA’s tasked with maintaining MQ series.
Java exists in IT departments probably because it is more forgiving, cross platform and the fantastic libraries available.
personally i will stick with C++, C#, Python, Perl, sh, sed, awk, egrep, make, .bat, Javascript, HTML, VBA, and occasionally java. choice depends on the task in hand, the resources & skillsets available and what the boss wants.

@Christian Felde (January 9th, 2011 – 18:07) – “I didn’t create the code, just re-ran the tests.”

You “just re-ran the tests” that were discarded back in 2005 and replaced by http://shootout.alioth.debian.org/

You chose to re-run “obviously flawed” out-dated programs.

If by flawed you imply not fully optimized C++ code (or Java code for that matter), that might be. But it still tests any improvements in the JVM since 2005.

The website you took the programs tells us – “Despite its obvious flaws…”

You don’t seem to have any idea what’s wrong as-benchmark-tasks with the programs you have chosen to publicise.

Well, there are two things:

1: Note the dates please
2: JVM retesting is still interesting (as stated very close to the top)

1: I did note the dates – my guess is that Keith Lea added his “UPDATE July 2010 – Despite its obvious flaws…” as a direct response to this blog post.

2: You aren’t doing “JVM retesting”! This doesn’t test “any improvements in the JVM since 2005”! You aren’t using the same Hardware and OS, or g++.

Garbage In, Garbage Out.

I think you’re too clever for – “I didn’t create the code, just re-ran the tests.” – to be an adequate excuse for not thinking about what the programs are actually doing 😉

C++/JVM in 2005 gives a relative benchmark re-run by me, so yes, it does test the updates on the JVM.

What “C++/JVM in 2005”?

Are you saying that in 2005 *you* made these same measurements on “a new Rackspace Cloud Server of their biggest kind (most CPU and 15.5G RAM) and booted it up with Debian 5.0” but using an older JVM?

Debian 5.0 wasn’t released until February 2009, so how could you?

GCC 4.3.2 wasn’t released until August 27, 2008, so how could you?

You haven’t *only* changed the JVM – that’s why you aren’t doing “JVM retesting”.

But the bigger issue is GIGO, think about what the programs are actually doing.

I don’t understand why this is so bloody difficult to understand.

Ratio A = 1
Ratio B = 0.9

You tell me the difference in ratio A and B..

> You tell me the difference in ratio A and B.

Ratio A= A_C++ / A_Java

Ratio B = B_C++ / B_Java

A_C++ != B_C++ so there’s no constant in your ratios and so the ratios aren’t comparable.

And of course the A_C++ programs were likely tweaked and optimised for completely different hardware than the hardware you arbitrarily chose to measure them on.

The constant in these tests are the code, as in the source code. So, if there are C++ compiler improvements or JVM improvements that deliver more optimized code (but based on the same source) then this is reflected in the ratios.

Your c++ codes are poor, you should rewrite it again or remove it.
A capable c++ programmer would not use c++ like you did.
Any language could be inefficiency if the programmers are lack of skills.

Okay so a java programmer writes and/or tweaks C++ on machines and configurations that are probably dubious at best and then runs benchmarks, proving exactly that a Java programmer far removed from the actual hardware knows nothing about benchmarks and c/c++.

Further are you actually trying to prove that a VM interpreting instructions is faster than native binary code? The tests prove nothing but your lack of hardware comprehension. No, I repeat no VM will ever compete with a properly written machine code native to that platform. OTOH a VM can easily read and write machine code directly. After all you do compile class files for a particular platform and all the JVM’s are hardware specific, ergo the position that one language is faster than the other is untenable as you are not comparing laguages but a particular VM against native execution. Native will win everytime by far more a factor than any benchmark test will show.

Just be happy you can code something and stop trying to prove the ridiculous.

Even if JAVA performs so well, still C++ has a role in it. Hotspot VM is written in C++ with JAVA based class libraries. If JAVA performed well, then its also the C++ code that performed well. The question is how well a VM is implemented.

But one thing I don’t like about JAVA is GC why run that extra GC thread in so many servers/devices around the world, when where to free things can be decided by careful human effort(its more effort though). It will help if JAVA standard mandates that extra GC thread has to be run only using solar energy 🙂

Umm.. The most popular app is the internet. It uses Java, LAMP, Ruby on Rails. Get over it C++ people. They’re two different languages, one an outdated bloated difficult to learn 80’s language, the other an easier to learn elegant syntax 90’s / 00’s language which runs fast and anywhere.

Another point, who’s going to be developing C++ for devices when everything is iOS / Android (Obj-C / Java for apps), Windows is dying a slow and painful death, don’t argue, and people don’t use PCs anymore? C++ is becoming increasingly irrelevant and it won’t come back. For scientific computing with CUDA and OpenCL, sure C++ will be used, but it’s a niche.

The point is that the VM is fast enough! And the simplicity, scalability and ‘portability’ (not a real thing in Java’s case) make it the clear winner in the contest.

The argument that only people without comp. sci. degrees are worthy of being a coder, so therefore only C++ people know what they’re doing are just silly.

I’m a fan of getting stuff done, fast and right! Java makes that so much easier than C++. End of story.

In LAMP, Linux is written in C and Assembly, Apache in C and Forth, MySQL in C and C++, and PHP in C (w/ Facebook’s hhvm written in C/C++). Ruby on Rails, is written in Ruby, which is written in C. Another popular (and quickly growing) http server is ngnix, written in C. Web browsers are mostly written in C++. Google’s core server systems are written in C++. Chrome on Android does most of the work in C++. The largest chunk of the Android OS is written in C++. Pretty much all OS networking stacks are written in C or C++. Even, both iOS and Android support writing code in C++. If C/C++ dies, it kills most of the innovation in tools that have allowed the Internet to flourish.

Java only makes programming easier than C++ if you’re making use of some areas of the API where C++ is lacking in library support or you are poor at programming. My Java programs are rather verbose because of Sun/Oracle design decisions, requiring extra coding time and I can’t count the number of problems I’ve seen that were because of the JavaVM. The lack of default values for parameters causes maintenance problems, and inability to overload operators makes syntax a royal mess a times, with no fix. So much for my code being simple.

As for running anywhere, Java on iOS is outside of the SDK agreement. Android uses a subset of the Java API (which got them sued), doesn’t run actual Java bytecode, and they’re probably shifting to running native apps. PC’s see more PUP’s installed by Oracle than actual Java programs. Java has been relegated to server environments where it competes against things like PHP, Ruby on Rails, Django, ASP.NET, and NodeJS.

P.S. Fast enough is always relative. For example, high frequency stock traders have decided that the speed of light through fiber is too slow and supplement software speed with ASIC’s. On one of the benchmarks here I’m seeing 50% worse scaling performance from Java and 25x the execution times. So much for fast enough and scalability.

You must run c++ in debug mode because I got 10-15 times better performance on my nested loops in c++ compared to JAVA. This benchmark can’t be taken seriously.

There’s a place for both. There are areas where C++ is still and will continue to be used while C++ programmers become scarcer. So if you know C++ you can be sure you’ll have a job and excellent pay for some decades still at the very least.

There are also a number of other languages worth knowing. For web programming it would be PHP and perhaps ASP.NET. Objective-C if you’re targeting Apple systems. And with Windows’ continuing dominance on the desktop C# will keep you busy for quite sometime to come.

Not only did C++ do better in all the test cases I tried, but also the C++ codes were clearly developed by people who don’t know C++. In “methcall”, for example, there is no need in allocating objects using operator new. The person who created the test tried to imitate java’s object allocation, but that’s not the way things are done in C++. Allocating those objects can be allocated on the stack made the C++ code run faster than Java’s test(notice that in your graph, java is like 6*faster than C++). This tests SUCK.

Hardware-friendly code will always beat hardware-ignorant code of the same quality.

Java does not allow you to be hardware-friendly, it would defeat its idea – it is designed to be hardware-ignorant.

So I don’t think you can use the most of your processor with Java – can you? Can you use vectorized (SIMD) instructions? Can you avoid cache pollution when moving data you are not going to touch soon? Can you guarantee good spatial locality of your code by keeping functions that are call each other close together in the memory?

Compilers suck at all this, and require a lot of manual intervention even in C++ (e.g. pragmas and intrinsics). With JVM, it is next to impossible, because you cannot pass these kinds of hints to it. CPU vendors know that, that is why server-oriented CPUs like Bulldozer or Niagara expect high number of threads with low IPC count – because server software tends to use single core inefficiently.

Java is more popular in server world because it makes it easier to people who are not inclined to learn how CPU works in detail to write code. And on average, their code will work well, which means there’s business case for hiring them (and not paying too much).

No way, C/C++ are still much faster with graphics among other things
Develop a real application like CAD or 3D engine in Java
and get back to us

All this proves is that naive C++ written by Java developers is slower than Java.

If java is that good, why there isn’t any widely used browser based on java ? and we all know that all popular browser based on C++. Java has it’s own advantage for easy to use. One popular JVM (Oracle one) is built in C++ http://openjdk.java.net/groups/hotspot/, and some written in C. There’s no way jvm which built with C running some algorithm can exceed the performance of C running some algorithm. It can only be par at most 🙂

Please, run the tests again. As Tompa said, this is not serious. At least, I have got a good time reading the jokes, sorry the comments.

There is a reason you don’t see demos using java with the same kind of fidelity as those done in C/C++/Assembler. Simply because it’s not fast enough. You don’t have to trust me on this, you can try it out for yourself. I look forward to see people prove me wrong 🙂

Those are some biased tests, C++ just cannot be that slower compared to Java., it should be faster in pretty much every test, or at worst little bit behind. Perhaps start time of the Java was not considered?
Or someone fails at C++?

As already stated the C++ tests suck. Recode them in properly written c/c++ and watch it blow java away. C/C++ and not just C++ because keeping in mind that c++ has to be backward compatible with the standard library as well as the standard c++ library, which means you can write the c++ tests in straight vanilla ansi c and those technically should even be faster than c++ with all it’s stl abstractions. And as already stated, the jvm is written in C++ with various modules in assembly for each arch. This fact alone should tell you that java can never be faster than c/c++.
To even begin to argue that java is faster or even as fast as c++ means that we are talking about the jvm jit compiled version, not the jvm running in interpretted mode. So even in that case you are trying to argue that the jvm after jit compiling is a better optimizing compiler than c++ with all hand optimized and compiler tuned flags which is horsecrap. You might as well say then that any compiled language is better than hand optimized assembly code written by someone that knows the arch and how memory works. Absurd.
So this is why these tests are always flawed. They are always written by java only programmers that are trying to recreate what java does in c++, not writing proper c++. So in other words they are comparing apples to oranges


How does this crap continue to exist? Well-written C++ always has and always will be faster than well-written Java, because Java has one extra layer of crap to get to the OS. It isn’t native code, something turns it into native code. Anybody who really doesn’t see why that is slower shouldn’t be a programmer.


Use what you prefer, but stop pretending you can outdo native code with non-native code.

I program both C++ and Java.. I agree with nerdmaster in the following statement.

“Well-written C++ always has and always will be faster than well-written Java, because Java has one extra layer” called the virtual machine.

I ran the code with g++ 4.9 and java 1.7.0_60. After fixing some of the aweful C++ code and proper compiling, C++ wins 11 out of 12. Most notably wc was written with a more efficient IO algorithm in Java than C++ that killed C++ performance. The program sumcol gets nice benefits from using C’s input routines instead of C++’s slow routines. In methcall I stopped the program from unnecessarily using object pointers in C++, and bumped up the inline limit. Nestedloop showed HUGE gains from simply generating and using profiling information when compiling.

In the end, only objinst runs slower in C++ than in Java. In C++, people generally ensure their objects have a much more reasonable lifetime, but I didn’t find a scenario where allocating objects was faster in C++ (didn’t try malloc/calloc as they were optimized away). I guess Java needs some bright spot to compensate for requiring >2GB heap size to do a meaningful amount of work in strcat on a Core 2 Duo, when C++ appears to need <512MB.

Comments are closed.