How slow is Java compared to C.

Have you ever wondered which of the most popular programming languages ​​is actually the fastest or the best performing? To test this, I came up with a short script / program that has to calculate the sum of all numbers from 0 to 100000000 in a loop. This can be implemented as a console output in all languages ​​and requires a lot of computing power - so it is perfect for a comparison. For the most part, the result is as expected, but it is also surprising in some languages.

The order of the results is based on the most popular languages ​​from GitHub.

JavaScript (Node.js 6.11)

var sum = 0for (var i = 0; i <100000000; i ++) {sum + = i} console.log (sum);
$ time node time.js 4999999950000000 real 0m0.247s user 0m0.226s sys 0m0.017s

Python 3.6

sum = 0 for i inrange (100000000): sum + = i print (sum)
$ time python 4999999950000000 real 0m18.588s user 0m18.558s sys 0m0.019s

Java 1.8

publicclassTime {publicstaticvoid main (String [] args) {long sum = 0; for (long i = 0; i <100000000; i ++) {sum + = i;} System.out.println (sum);}}
$ time java Time 4999999950000000 real 0m0.177s user 0m0.145s sys 0m0.025s

Ruby 2.4

#! / usr / bin / ruby ​​sum = 0 for i in0..99999999 sum + = i endputs sum
$ time ruby ​​time.rb 4999999950000000 real 0m5.385s user 0m5.338s sys 0m0.026s


#! / usr / bin / php
$ time php time.php 4999999950000000 real 0m2.298s user 0m2.273s sys 0m0.014s

C ++

#include usingnamespace std; int main () {long sum = 0; for (long i = 0; i <100000000; i ++) {sum = sum + i;} cout << sum << endl; return0;}
$ time ./time4999999950000000 real 0m0.220s user 0m0.216s sys 0m0.002s


#include int main () {long sum = 0; for (long i = 0; i <100000000; i ++) {sum = sum + i;} printf ("% ld \ n", sum); return0;}
$ time ./time4999999950000000 real 0m0.212s user 0m0.208s sys 0m0.002s


Note: Bash is unfortunately overwhelmed with the large numbers. The script therefore works with a lower total sum, but even there comes to a runtime that is well above average.

#! / bin / bashsum = 0for i in {0..9999999}; doletsum = $ sum + $ idoneecho $ sum
$ time ./ 49999995000000 real 1m59.923s user 1m55.809s sys 0m3.687s

bar graph


That C, C ++ and Java lead the field is not surprising.

However, JavaScript is the first scripting language behind it, making it clear why it has established itself as the most widely used language on GitHub.

In terms of performance, PHP beats its direct competitors Python and Ruby by a good margin.

I even had to remove Bash from the bar chart because of the miserable result.