npm i benchmark
results
simple function call x 962,129 ops/sec ±2.62% (79 runs sampled)
object function call x 900,959 ops/sec ±2.13% (89 runs sampled)
Fastest is simple function call
Around 0.1 ms for 1000 calls
const {Benchmark} = require('benchmark'); | |
var suite = new Benchmark.Suite; | |
function normalFunctionCall (name, skill, age) { | |
const res = []; | |
if (name.length > 10) { | |
for (let i = 0; i < name.length; i++) { | |
res.push(name[i]); | |
} | |
} | |
else { | |
for (let i = 0; i < skill.length; i++) { | |
res.push(skill[i]); | |
} | |
} | |
const ageName = name + age; | |
for (const o of [name, skill, age, ageName]) { | |
if (ageName[`${o.length}`]) { | |
res.push(o); | |
} | |
else { | |
res.push(o, 42); | |
break; | |
} | |
} | |
const final = {}; | |
for (const i of res) { | |
final[i] = i; | |
} | |
return [final, res, final.length]; | |
} | |
function objectFunctionCall ({ name, skill, age }) { | |
const res = []; | |
if (name.length > 10) { | |
for (let i = 0; i < name.length; i++) { | |
res.push(name[i]); | |
} | |
} | |
else { | |
for (let i = 0; i < skill.length; i++) { | |
res.push(skill[i]); | |
break; | |
} | |
} | |
const ageName = name + age; | |
for (const o of [name, skill, age, ageName]) { | |
if (ageName[`${o.length}`]) { | |
res.push(o); | |
} | |
else { | |
res.push(o, 42); | |
} | |
} | |
const final = {}; | |
for (const i of res) { | |
final[i] = i; | |
} | |
return [final, res, final.length]; | |
} | |
let ret; | |
// add tests | |
suite | |
.add('simple function call', async function() { | |
ret = normalFunctionCall('aschen', 'nodejs', 28); | |
}) | |
.add('object function call', async function() { | |
ret = objectFunctionCall({ | |
name: 'aschen', skill: 'nodejs', age: 28 | |
}); | |
}) | |
.add('simple function call 2', async function() { | |
ret = normalFunctionCall('aschen', 'nodejs', 28); | |
}) | |
.add('object function call 2', async function() { | |
ret = objectFunctionCall({ | |
name: 'aschen', skill: 'nodejs', age: 28 | |
}); | |
}) | |
// 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({ }); |