As promised, more benchmarking results of comparing C++ to Java. This
time around, our first target will be the strcat program. This is one
that the C++ version rather bothered me -- I'm reasonably convinced
that anybody who could have written it would have immediately realized
that there was a drastically better way to do it. Here's some code:
#include <iostream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
int i, n = ((argc == 2) ? std::atoi(argv[1]) : 3000000);
std::string str;
str.reserve(6*n);
for (i=0; i<n; i++)
str += "hello\n";
std::cout << str.length() << std::endl;
return 0;
}
Despite being noticeably shorter and simpler than the original code,
this is still pretty fast.
Unfortunately, Java seems unwilling (or perhaps unable) to take
advantage of all the available memory, causing a bit of a timing
problem -- I normally try to get the fastest program to take at least
one second, but in this case Java ran out of memory before even the
slowest version too a second. Fortunately, the difference in speed is
large enough that the winner is pretty clear, though we only have one
significant digit in the times:
Java client: .9 seconds
Java Server: .7 seconds
C++: .1 seconds
A quick check shows that even when n was increased to 4000000, the
time for C++ stayed at .1 seconds. That indicates that the margin of
victory for C++ is probably closer to 10:1 than the 7:1 shown above. I
may start adding a better timing framework into the code to reduce
problems like this.
I was going to give the results for the sieve of Eratosthenes next,
but I've decided to delay that -- if I was trying to be partial, I'd
just publish some code with results like:
Java Client: 5.6 seconds
Java Server: 5.5 seconds
C++: 1.1 seconds
and leave it at that. OTOH, this test gives a chance to show quite a
bit more, especially about how the benchmarker can affect the results
while seeming to remain impartial.
--
Later,
Jerry.
The universe is a figment of its own imagination.