Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created September 6, 2017 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmeurer/1f68aed27d912bc9af5850377ccd6c7e to your computer and use it in GitHub Desktop.
Save bmeurer/1f68aed27d912bc9af5850377ccd6c7e 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 = 2e8;
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.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment