Created
January 26, 2022 08:38
-
-
Save Aschen/6a837c86edab8084dc659094ada8b197 to your computer and use it in GitHub Desktop.
Monomorphic vs Polymorphic function
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'); | |
var suite = new Benchmark.Suite; | |
function monomorphic (person) { | |
const array = []; | |
for (let i = 10; i--; ) { | |
array.push(person.age * i); | |
} | |
if (array[0] % 2) { | |
return array.map(e => e + 42); | |
} | |
return array.map(e => e + 21); | |
} | |
function polymorphic (person) { | |
const array = []; | |
for (let i = 10; i--; ) { | |
array.push(person.age * i); | |
} | |
if (array[0] % 2) { | |
return array.map(e => e + 42); | |
} | |
return array.map(e => e + 21); | |
} | |
let ret; | |
// add tests | |
suite | |
.add('monomorphic function', function() { | |
ret = monomorphic({ age: 21, name: 'Aschen' }); | |
ret = monomorphic({ age: 29, name: 'Aschen' }); | |
}) | |
.add('polymorphic function', function() { | |
ret = polymorphic({ age: 21, name: 'Aschen' }); | |
ret = polymorphic({ name: 'Aschen', age: 29 }); | |
}) | |
// 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(); | |
/* | |
$ node node/mono-vs-poly.js | |
monomorphic function x 3,975,995 ops/sec ±2.50% (86 runs sampled) | |
polymorphic function x 2,111,454 ops/sec ±0.38% (91 runs sampled) | |
Fastest is monomorphic function | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment