BY Simmi Kava16 Mar 2021 Edit
Is 'instanceof' an expensive operation in JavaScript

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.

BY Simmi Kava
LikeCommentSave
LikeCommentSaveShare
0
Categories
General
YantraJS
Developer Guides
Tutorials
Web Atoms Updates

POPULAR POSTS
17 Mar 2021
LATEST ACTIVITY
Simmi Kava
commented this post.
Simmi Kava
liked this post.
Show more
ARCHIVES
2025
2024
2023
2022
TAGS
javascript (56)
developer (25)
javascriptdeveloper (16)
Xamarin.Forms (16)
Html (14)
typescript (12)
webatoms (12)
xamarin (11)
coding (10)
web-atoms (10)
arrays (9)
android (8)
javascript-developer (8)
csharp (7)
dotnet (7)
css (6)
update (6)
dotnet-standard (5)
function (5)
iOS (5)
methods (4)




Web Atoms: JSX (TSX + TypeScript) for Xamarin.Forms, Hot Reload Your App in Production Environment

PlaygroundSamples Repository