
As we know 'instanceof'
allows to check type of object at run time which may be necessary in few cases.
So, is it an expensive operation in JavaScript? It may be an expensive operation in certain scenario. Let's learn how and why?
class Shape {
}
class Circle extends Shape{
}
var c = new Circle();
// this is one step call
if(c instanceof Circle) {
}
// this is two step call
if(c instanceof Shape) {
}
// this is three step call
if(c instanceof Object) {
}
why is the below a two step call?
// this is two step call
if(c instanceof Shape) {
}
Why?
This is how you have to traverse to verify if c is instance of shape
c.__proto__ === Shape //false
c.__proto__.__proto__.constructor === Shape //true
The deeper you want to traverse, complex it becomes. So, what is the suggested alternative to 'instanceof'? Object notation as shown below:-
var c1 = {
isCircle: true,
isShape: true
};
// this is single step call
if(c1.isCircle) {
}
// this is single step call
if(c1.isShape) {
}
Even Esprima
and Typescript
compiler do not use classes approach as they are slow to construct compare to object.
Why?
As each creation will require super to be executed. So, when you have too many number of items, it will be slow to create and slow to inspect.
So to conclude, avoid using 'instanceof'
when number of elements to inspect are very high.
![]() | ![]() | ![]() | ![]() |
Like | Comment | Save | Share |