吴烜_中文编程
吴烜_中文编程

Reputation: 548

nonlinear performance when exteme for loop

This is a simple loop, and I'm trying to benchmark the performance.

var extremeLoop=function(n){
    var time=new Date()
    var t=0;
    for(var i=0;i<n;i++){
       t=1;
    }
    return (new Date())-time;
}

Tested in Chrome:

extremeLoop(100000000)
305
extremeLoop(1000000000)
3075
extremeLoop(1500000000)
19690
extremeLoop(2000000000)
29448
extremeLoop(10000000000)
174129

I agree it's not important, but I wonder why this is?

Upvotes: 0

Views: 81

Answers (2)

Codeman
Codeman

Reputation: 12375

A Javascript Number is 64-bit as per the ECMAScript spec, so that's not why this is happening.

The spec actually states exactly how the for-loop is executed:

ECMA for loop

This is likely happening because of the overhead of type checking in the comparison algorithm.

The loop might be optimized by forcing Number comparison:

for(var i = 0; +i < +n; i++)

Or possibly by manipulating the termination condition:

for(var i = 0; +i != +n; i++)

Here's a JSFiddle showing your example and my two examples.

I got 14664 output for the highest number in your extremeLoop here.

The value for the first "fix" is 14383. Not much of a change.

The second fix provides a value of 14306. Still not much of a change.

So the conclusion is likely that the VM itself is storing array values in 2 locations. The 32-bit issue is the problem, after all.

It should be understood that this is not an issue with the Javascript language. As stated above, Number is 64 bits in ECMAScript implementations. But the underlying VM (Chrome's V8 in this case) is storing a concatenation of 2 numbers in 2 different locations.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234857

My guess is that when n is larger than the maximum 32-bit integer value, you end up doing more expensive operations in the loop increment/test code.

Alternatively, it may be that when the loop takes longer to run, there's more of a chance that the system will pause the process because of overall system load, etc. Since you're measuring performance by wall clock time, that would affect the results.

Upvotes: 1

Related Questions