Skip to content

Instantly share code, notes, and snippets.

@robpalme
Forked from bmeurer/bench-james.js
Last active September 6, 2017 22:01
Show Gist options
  • Save robpalme/9575fc27d9bab1168b3541039396e7a7 to your computer and use it in GitHub Desktop.
Save robpalme/9575fc27d9bab1168b3541039396e7a7 to your computer and use it in GitHub Desktop.
// Micro-benchmark to answer the question in https://twitter.com/thejameskyle/status/905403367949647874
if (typeof console === 'undefined') console = {log:print};
var closuresOriginal = (function() {
const outer = a => {
const inner = b => a + b;
return inner(2);
};
return function closuresOriginal(a) {
return outer(a);
}
});
var closuresInitialTransform = (function() {
const inner = (a, b) => a + b;
const outer = a => inner(a, 2);
return function closuresInitialTransform(a) {
return outer(a);
}
});
var closuresSymbolTransform = (function() {
const _a = Symbol('a');
const inner = b => inner[_a] + b;
const outer = a => {
inner[_a] = a;
return inner(2);
};
return function closuresSymbolTransform(a) {
return outer(a);
}
});
var closuresBind = (function() {
const inner = (a, b) => a + b;
const outer = inner.bind(undefined, 2);
return function closuresBind(a) {
return outer(a);
}
});
var TESTS = [
closuresOriginal,
closuresInitialTransform,
closuresSymbolTransform,
closuresBind
];
var a = 40;
var n = 2e7;
function test(fn) {
var result;
for (var i = 0; i < n; ++i) result = fn(a);
return result;
}
for (var j = 0; j < TESTS.length; ++j) {
test(TESTS[j]);
}
for (var j = 0; j < TESTS.length; ++j) {
var startTime = Date.now();
test(TESTS[j]);
console.log(TESTS[j].name + ':', (Date.now() - startTime), 'ms.');
}
@robpalme
Copy link
Author

robpalme commented Sep 6, 2017

Results for the setup cost of these forms:

closuresOriginal: 670 ms.
closuresInitialTransform: 925 ms.
closuresSymbolTransform: 2206 ms.
closuresBind: 1223 ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment