Last active
April 18, 2024 18:11
-
-
Save webstrand/c86e2840cd45f0536d943afa71f6b7e2 to your computer and use it in GitHub Desktop.
Comparing the performance of instanceof against tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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