javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -
consider code:
test = function() { } t = new test(); (var = 0; < 8; i++) { result = t instanceof test; }
if change number of iterations 8 9, loop take 100 times longer complete in latest version of firefox (41.0.1). tested on 2 different pcs , magic limit 8.
here jsperf test used: http://jsperf.com/instanceof-8-times-vs-9-times
does have idea why might happen? seems specific instanceof. not happen if else object, example check property.
note: filed bugzilla bug this.
jan de mooij mozilla team has posted details in bugzilla thread. here's simplistic interpretation of highly technical answers:
in i < 8
case, firefox smart enough hoist result = t instanceof test;
statement out of loop (according tests, doesn't seem omit altogether). in i < 9
case, apparently doesn't optimization.
why? reason not clear, related fact 9 iterations threshold above function considered "hot" enough run through jit compiler. i < 8
case stays in interpreter. (i don't see why jit-ing exclude hoisting, apparently in current version of engine.)
interestingly, 8-iteration threshold doesn't seem universal. example, if replace our own prototype (test
) built-in prototype (e.g. customevent
), hoisting doesn't seem occur regardless of number of iterations (relevant jsperf):
for (var = 0; < 8; i++) { //or < 9 t instanceof customevent; }
coming original code using test
prototype, why performance bad in i < 9
case? related how jsperf works. "setup" code not executed once – run once "per test". every time click run, jsperf runs hundreds of "tests", each test comprising thousands of iterations. setup code run hundreds of times. means there hundreds of different prototype objects named test
in program, created line:
test = function(){ }
the ion jit optimizing compiler can optimize case in using instanceof
on same prototype object many times (as customevent
in this test case), when notices there more 1 object same name, apparently throws hands in air.
jan has rightly pointed out not affect many real-world scripts because single identifier associated single prototype object (e.g. have class foobar
, defined once , never re-defined). jsperf re-defines prototypes hundreds of times. seems me fact casts serious doubt on published jsperf results include prototype definitions, except explicitly avoid redefinition using globals (as in test case) – perhaps important conclusion this.
for example, jsperf tests linked question: is using instanceof operator in javascript performance issue? worthless, since define prototypes in setup code.
Comments
Post a Comment