C++ and Java's Looping on Strings performance comparisons

Viewed 155

I have made some performance test against C++ (implemented in Visual Studio Community Edition 2015) and Java (1.7) for loops.
The following are the source code:

Java:

long startTime = 0;
long endTime = 0;
long totalTime = 0;

startTime = System.currentTimeMillis();
for (long counter = 0; counter < numberOfIterations; counter++)
{
    System.out.println("01234");
}
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;

C++ (Windows based, release version x64, optimized for speed):

ULONGLONG startTime = 0;
ULONGLONG endTime = 0;
ULONGLONG elapsedTime = 0;

startTime = GetTickCount64();
for (LONGLONG counter = 0; counter < numberOfIterations; counter++)
{
    cout << "01234" << endl;
}
endTime = GetTickCount64();
elapsedTime = endTime - startTime;

The results really surprised me when I spin/loop them for 100,000 times. Here they are:
Java:

  • 1st attempt: 31,361 milliseconds
  • 2nd attempt: 6,316 milliseconds
  • 3rd attempt: 6,865 milliseconds

C++:

  • 1st attempt: 40,000 milliseconds
  • 2nd attempt: 37,703 milliseconds
  • 3rd attempt: 20,734 milliseconds

Then I had another set of test case

Java:

long startTime = 0;
long endTime = 0;
long totalTime = 0;
startTime = System.currentTimeMillis();
for(long counter = 0; counter < numberOfIterations; counter++) {
    String tempString = new String("test");
}
endTime = System.currentTimeMillis();

C++ (Windows based, release version x64, optimized for speed):

ULONGLONG startTime = 0;
ULONGLONG endTime = 0;
ULONGLONG elapsedTime = 0;

startTime = GetTickCount64();
for (LONGLONG counter = 0; counter < numberOfIterations; counter++)
{
    string tempString = "test";
}
endTime = GetTickCount64();
elapsedTime = endTime - startTime;

Again, the results is really more surprising, when I spin/loop them for 10,000,000 times. Here they are: Java

  • 1st attempt: 7 milliseconds
  • 2nd attempt: 7 milliseconds
  • 3rd attempt: 7 milliseconds

C++:

  • 1st attempt: 125 milliseconds
  • 2nd attempt: 125 milliseconds
  • 3rd attempt: 125 milliseconds

But on empty loops C++.

Before doing this test I was actually thinking that C++ will always out perform Java in low level or OS/Platform specific implementation. But, in this case, does this mean that Java has more efficient way of handling Strings specially if it is already in volumes?



Thanks

1 Answers
Related