在V8(Chrome的JS引擎),似乎有小到無的性能損失:
> 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
火狐顯示相同的行爲。
去了一下這裏瘋狂,但:
> 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
我認爲它是安全的假設沒有性能損失,如果它可以到10,000類鑽,而不是看1毫秒的性能差異:)
相關:https://stackoverflow.com/a/45656957/632951 – Pacerier 2017-08-13 04:19:19