Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding JavaScript performance variance

http://jsfiddle.net/6L2pJ/

var test = function () {
    var i,
        a,
        startTime;

    startTime = new Date().getTime();

    for (i = 0; i < 3000000000; i = i + 1) {
        a = i % 5;   
    }
    console.log(a); //prevent dead code eliminiation
    return new Date().getTime() - startTime;
};

var results = [];

for (var i = 0; i < 5; i = i + 1) {
    results.push(test());
}

for (var i = 0; i < results.length; i = i + 1) {
    console.log('Time needed: ' + results[i] + 'ms');
}

Results in:

First execution:

Time needed: 13654ms 
Time needed: 32192ms 
Time needed: 33167ms 
Time needed: 33587ms 
Time needed: 33630ms 

Second execution:

Time needed: 14004ms 
Time needed: 32965ms 
Time needed: 33705ms 
Time needed: 33923ms 
Time needed: 33727ms 

Third execution:

Time needed: 13124ms 
Time needed: 30706ms 
Time needed: 31555ms
Time needed: 32275ms
Time needed: 32752ms 

What is the reason for the jump from first to second row?

My setup:

  • Ubuntu 13.10

  • Google Chrome 36.0.1985.125 (Mozilla Firefox 30.0 giving same kind of results)

EDIT:

I modified the code leaving it semantically the same but inlining everything. Interestingly it does not only speed up the execution significantly but it also removes the phenomena that I described above to a great extent. A slight jump is still noticable though.

Modified code:

http://jsfiddle.net/cay69/

Results:

First execution:

Time needed: 13786ms 
Time needed: 14402ms 
Time needed: 14261ms 
Time needed: 14355ms 
Time needed: 14444ms 

Second execution:

Time needed: 13778ms 
Time needed: 14293ms 
Time needed: 14236ms
Time needed: 14459ms 
Time needed: 14728ms 

Third execution:

Time needed: 13639ms 
Time needed: 14375ms 
Time needed: 13824ms 
Time needed: 14125ms 
Time needed: 14081ms
like image 366
ben Avatar asked Aug 03 '14 20:08

ben


1 Answers

After a bit testing, I think I have pin-pointed what may be causing the difference. It must have something to do with type I think.

 var i,
     a = 0,
     startTime;

var a = 0 gives me a uniformed result with an overall faster performance, on the other hand var a = "0" gives me the same result as yours: the first one is somewhat faster.

I have no clue why this happens.

like image 52
Derek 朕會功夫 Avatar answered Nov 15 '22 01:11

Derek 朕會功夫