I am just speculating here and the title of my post is just based on some tests I performed in my spare time; but, according to them, based on dynamic array lists and strings, Java is far faster than C++.
The simple Java program is this:
package jtest; import java.util.*; public class Main { public static void testPtrList(int z) { ArrayList<String> list = new ArrayList<String>(); int z0 = z * 2000; for (int i = z0; i < z0 + 2000; i++) { String s = "X-"; s += i; list.add(s); } } public static void main(String... args) { long t0 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { if (i % 1000 == 0) System.out.println(i); testPtrList(i); } long tz = System.currentTimeMillis(); System.out.println("Milliseconds: " + (tz - t0)); } }
As you can see, the test is quite simple, calls a method 10000 times and the method creates 2000 strings and adds them into a dynamic array list.
I also implemented the same stuff using STL in C++:
#include <string> #include <vector> #include <iostream> using namespace std; void testList(int i) { char aux[10]; int z0 = i * 2000; vector<string> v; for (int i = z0; i < z0 + 2000; i++) { string s("X-"); sprintf(aux, "%d", i); s += aux; v.push_back(s); } } int main() { for (int i = 0; i < 10000; i++) { if (i % 1000 == 0) printf("%d\n", i); testList(i); } return 0; }
The results:
In my box, the C++ program is executed in 15 seconds approximately, but the program executed using the HotSpot JVM, is executed in….
in…
2 SECONDS!!!
I know my test is tiny and it cannot be useful as a real world performance benchmark, but it says some interesting things:
- There are things where Java outperforms C++ with almost no effort.
- I implemented the C++ thing using STL; I have also created my own String and Array classes [as optimized as I could] and implemented the same test using them: the performance was similar. My classes were implemented using full pointers [trying to mimic the Java behavior]. So, I think the problem is not in the code, but in the compiler.
- I replaced g++ to llvm-g++ and the C++ program was executed in about 10 seconds [33% faster than the g++ binary].
- I implemented a similar thing in C# and tested using Mono, but the thing got executed in 21 seconds; so, Mono is behind Java right now; I have no environment to run such C# program using the .NET Framework [and running it inside a virtual machine is not fair at all], so I cannot infer anything about this.
No matter if the performance is inferior in other areas, my simple test demonstrates the amazing development of the Java JIT compiler.
Ah! I have also compiled my Java program using gcj [to native code]…. and the execution took 30 seconds approx… so… gcj is behind Java right now too.
I can’t seem to fully load this post from my iphone!!!!
Nice work!
The std string implementation in c++ is known to be a little slow. Would be interesting to profile this and see if that’s where the cyles are being eaten up.
Regards
Rich