user1494173
user1494173

Reputation: 169

Javascript/JSPerf Looping Performance

Lately I've been really digging into JS performance, and this other question of mine Javascript Array Performance lead me to this problem.

Problem: Looping using a global variable seems to be WAY faster than iterating using a local variable, can anyone explain to me, why is that ? --- This has just been my error in JSPerf understanding, but Problem 2 still remains, but I guess there is no real answer to it, the rest has been discussed with @Igor-Raush in chat --- Or so I thought, that test in JSPerf is still 100x faster, then the basic version ...

You can see this behavior here: http://jsperf.com/fastest-array-loops-in-javascript/420 -- I added the last two tests, but the last one did not work, for some reason, so I removed its contents

Problem 2 (extra question, kind of related): Why is that when you run the tests on JSPerf individually ( for some of them ), their performance is consistently COMPLETELY different, than when they are all ran at once ? ( You can see this on While length-- test )


I am testing this, because ( If you went to my other question ), I do not believe that looping over my array should be as slow as it is, in the tests.

Upvotes: 0

Views: 603

Answers (1)

Igor Raush
Igor Raush

Reputation: 15240

Problem 1

The reason for the vast performance "improvement" in the global case is that you are initializing a global it = 0 in the preparation code. In JSPerf, each test case is run for multiple trials. The first time your test case is run, it increments the global it until it exceeds arr.length.

The next time (and all subsequent times) the test case is run, the condition it < arr.length evaluates to false, and the loop is not even entered. This is not the case in the "While loop, basic" test case where var i = 0 is initialized before every trial.

You can see in this Plunker that using a global iterator variable is approximately twice as slow as using a local one (open console to see results).

Problem 2

One possible reason for high variance in performance is that running all tests could cause the array to be cached closer to CPU by the time the later test cases are run. When you run a test case stand-alone, it may require memory access. For something as basic as for/while iteration, memory access is a real bottleneck. However, this is just one possible explanation.

Upvotes: 1

Related Questions