Reputation: 2712
I'm using JS for solving tasks on Project Euler now and then. For one of the tasks I had to iterate some 600 billion consecutive numbers. To my surprise, it took about 14 hours in NodeJS.
Just run the snippet below and your browser is stuck for hours (I tried Chrome and Firefox):
console.time('t')
for (var i = 0; i < 600851475143; i++) {}
console.timeEnd('t')
For comparison, in Java it runs about 200ms on my machine, 4 seconds if I compute square root of every i
.
What's happening???
UPDATE: I know that iterating every number was not the right way to solve this particluar PE problem. The question is not about that.
UPDATE 2: I was mistaken about Java. As people correctly pointed out, it just physically can't run this fast. I was just using the wrong number, sorry.
Upvotes: 2
Views: 1802
Reputation: 140236
First of all both 200ms and 4 seconds are completely ridiculous because your processor can most likely only do up to 4 billion cycles per second (4 GHz), even if one loop iteration costed 1 cycle it would still take at least 150 seconds. However even an empty loop will cost at least 3 cycles per iteration (assuming it's not optimized out), calculating square root adds 5-10 per iteration so you simply didn't do 600 billion square roots in 4 seconds.
And I cannot even reproduce, the following takes forever to run as expected:
class Test {
public static void main(String[] args) {
for (long i = 0; i < 600851475143L; ++i) {
}
}
}
Then
$ java -version
java version "1.7.0_55"
OpenJDK Runtime Environment (IcedTea 2.4.7) (7u55-2.4.7-1ubuntu1)
OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)
$ javac test.java
$ java -cp . Test
Upvotes: 4