-
-
Save robpalme/9575fc27d9bab1168b3541039396e7a7 to your computer and use it in GitHub Desktop.
Setup cost: Micro-benchmark for https://twitter.com/thejameskyle/status/905403367949647874
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results for the setup cost of these forms:
closuresOriginal: 670 ms.
closuresInitialTransform: 925 ms.
closuresSymbolTransform: 2206 ms.
closuresBind: 1223 ms.