How exactly does Javascript instanceof work? Is it slow style?

前端 未结 3 488
面向向阳花
面向向阳花 2021-01-04 19:24

How does the performance of instanceof fair for \"huge libraries\"?

Does it travel up the prototype chain one by one, similar to this?

3条回答
  •  抹茶落季
    2021-01-04 20:26

    in V8 (Chrome's JS engine), there seems to be little-to-no performance hit:

    > function A(){}
    > function B(){}
    > function C(){}
    > function D(){}
    > B.prototype = new A();
    > C.prototype = new B();
    > D.prototype = new C();
    > 
    > var objA = new A();
    > var objD = new D();
    > 
    > var start = (+new Date()); for(var i=0; i<10000000; i++){ objA instanceof A } console.log((+new Date()) - start);
    138
    > var start = (+new Date()); for(var i=0; i<10000000; i++){ objD instanceof A } console.log((+new Date()) - start);
    138
    

    Firefox shows identical behavior.

    Going a bit crazy here, but:

    > var classes = [];
    > for(var i=0; i<10000; i++){
    >   classes[i] = function(){};
    >   i && (classes[i].prototype = new (classes[i-1])());
    > }
    >
    > var obj0 = new classes[0],
    >  obj9999 = new classes[9999];
    >
    > var start = (+new Date()); for(var i=0; i<10000000; i++){ obj0   instanceof classes[0] } console.log((+new Date()) - start);
    138
    > var start = (+new Date()); for(var i=0; i<10000000; i++){ obj999 instanceof classes[0] } console.log((+new Date()) - start);
    138
    

    I think it's safe to assume there is no performance hit if it can drill through 10,000 classes and not see 1 ms performance difference :)

提交回复
热议问题