Skip to content

Instantly share code, notes, and snippets.

@webstrand
Last active April 18, 2024 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webstrand/c86e2840cd45f0536d943afa71f6b7e2 to your computer and use it in GitHub Desktop.
Save webstrand/c86e2840cd45f0536d943afa71f6b7e2 to your computer and use it in GitHub Desktop.
Comparing the performance of instanceof against tags
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
class Base {
type = "base"
}
class Child extends Base {
type = "child"
}
function createBaseObj() {
return {
type: 'base'
}
}
function createChildObj() {
return {
type: 'child'
}
}
const base = new Base();
const child = new Child();
const baseObj = createBaseObj();
const childObj = createChildObj();
// Adding tests
suite.add('class based', function() {
((base, child) => {
if (base instanceof Child) {
return true;
}
if (child instanceof Base) {
return true;
}
})(base, child);
})
.add('tag based', function() {
((base, child) => {
if (base.type === 'child') {
return true;
}
if (child.type === 'base') {
return true;
}
})(baseObj, childObj);
})
.add('constructor based', function() {
((base, child) => {
if (base.constructor === Child) {
return true;
}
if (child.constructor === Base) {
return true;
}
})(base, child);
})
// Add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// Run async
.run({ 'async': false });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment