You are testing it in two different environments. To make it a fair test, I decided to test it in similar environments (same host, 2GHz AMD A10-6800K processor as reported by cat /proc/cpuinfo
):
Javascrtipt – using node
binary version 0.10.25 on Linux executed from bash prompt. Results were consistent around 83ms. I had to remove window.onload
wrapper, otherwise it was your code as is.
C++ – I had to remove the inclusion of stdafx.h
to get it to compile. I also removed the call to getchar()
as it was unnecessary. I compiled with g++ 4.8.4 with defaults and again ran it from bash prompt. The results varied between 10ms and 20ms.
When I redirected the standard output to a file, Javascript executed in 42ms, while C++ took 1 ms.
Which is a result that would be in the range of what one would expect when comparing a native binary compiled vs just-in-time compiled languages for this type of workload. Note however, that when the code is I/O heavy, as in your example, the difference will be largely negated, and if you test in different I/O subsystems, the one with the faster I/O will win regardless of the efficiency of the rest of the code.
I believe the 2000 ms order of magnitude result you are observing in C++ is connected to the console you are using (Windows default CMD.EXE ?) being not very efficient with the standard output processing.
Note, that I did verify with strace
that in both cases in my test I/O was being done in a similar way – repeated calls to write()
– one per line. If one was buffering, for example, and the other was not, it could have made a difference big enough to negate the speed differences in the rest of the code.
2
solved Why is it faster to print to the javascript console than printing to C++ console? [closed]