Created
October 19, 2020 18:14
-
-
Save SMotaal/d9b0c2b796107e644898df0fe264d740 to your computer and use it in GitHub Desktop.
Benchmark: Inline Closures vs. Nested Functions
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
export default (class { | |
MakeInlineClosure() { | |
const messages = []; | |
return (message => { { messages.push(message); } }); | |
} | |
['InlineClosure (ahead-of-time)'] = ({MakeInlineClosure, InlineClosure = MakeInlineClosure()} = this) => () => InlineClosure('test'); | |
['InlineClosure (just-in-time)'] = ({MakeInlineClosure} = this) => () => MakeInlineClosure()('test'); | |
MakeNestedFunction(){ | |
const messages = []; | |
const push = function (message) { messages.push(message); }; | |
return (message => { push(message) }); | |
} | |
['NestedFunction (ahead-of-time)'] = ({MakeNestedFunction, NestedFunction = MakeNestedFunction()} = this) => () => NestedFunction('test'); | |
['NestedFunction (just-in-time)'] = ({MakeNestedFunction} = this) => () => MakeNestedFunction()('test'); | |
MakeNestedArrowFunction() { | |
const messages = []; | |
const push = message => messages.push(message); | |
return (message => { push(message) }); | |
} | |
['NestedArrowFunction (ahead-of-time)'] = ({MakeNestedArrowFunction, NestedArrowFunction = MakeNestedArrowFunction()} = this) => () => NestedArrowFunction('test'); | |
['NestedArrowFunction (just-in-time)'] = ({MakeNestedArrowFunction} = this) => () => MakeNestedArrowFunction()('test'); | |
async run(result = {}, { iterations = 10000, warmup = true } = {}) { | |
await this.iterate(result['(baseline)'] = { iterations, warmup }, () => {}); | |
for (const description in this) | |
await this.iterate(result[description] = { description, iterations, warmup }, await this[description](this)); | |
return result; | |
} | |
async iterate(result, execute) { | |
for (let i = result.warmup === true ? 100 : result.warmup > 0 ? result.warmup : 0; i--; await execute()); | |
result.start = Date.now(); | |
for (let i = result.iterations >= 0 ? result.iterations : result.iterations = 1; i--; await execute()); | |
result.duration = (result.end = Date.now()) - result.start; | |
return result; | |
} | |
static async run() { | |
console.table(await (new this).run(), ['iterations', 'duration']); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment