Skip to content

Instantly share code, notes, and snippets.

@hinell
Last active June 8, 2019 13:34
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 hinell/41be40402f661d8fcfadf07d614d6c87 to your computer and use it in GitHub Desktop.
Save hinell/41be40402f661d8fcfadf07d614d6c87 to your computer and use it in GitHub Desktop.
Measures performance of the variable assignment by destructuring. See my post here: https://twitter.com/biteofpie/status/1137079144301379586
function bench (name, iterations = 500, fn) {
const t0 = performance.now();
for (let i = 0; i < iterations; i++) fn(i)
let d = performance.now() - t0;
d = Math.ceil(d);
let ops = iterations / d;
ops = Math.ceil(ops);
ops = new Intl.NumberFormat('en').format(ops);
console.log(`${name} took: ~%f ms or ~%s ops/ms`, d, ops)
}
obj = {
abcd0: "foo0",
abcd1: "foo1",
abcd2: "foo2",
abcd3: "fo03",
};
// Number of times we run the tests
iters = 10 ** 7;
console.clear();
// Normal variable assignments of obj props
bench(`assign object vars`, iters, function (i){
var abcd0 = obj.abcd0;
var abcd1 = obj.abcd1;
var abcd2 = obj.abcd2;
var abcd3 = obj.abcd3;
return abcd0 + abcd1 + abcd2 + abcd3 + i;
});
// By destructuring
bench(`destruct object vars`, iters, function (i){
var { abcd0, abcd1, abcd2, abcd3 } = obj;
return abcd0 + abcd1 + abcd2 + abcd3 + i;
})
var i = 0;
// Asignment inside function parameters
bench(`destruct object func`, iters, function (i){
(function({ abcd0, abcd1, abcd2, abcd3 }){
return abcd0 + abcd1 + abcd2 + abcd3 + i;
})(obj);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment