Skip to content

Instantly share code, notes, and snippets.

@Aschen
Created May 11, 2022 17:39
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 Aschen/b75da687a7b6ed5419459837d8d1514b to your computer and use it in GitHub Desktop.
Save Aschen/b75da687a7b6ed5419459837d8d1514b to your computer and use it in GitHub Desktop.
Call function with simple argument vs object argument

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({ });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment