Skip to content

Instantly share code, notes, and snippets.

@robpalme
Created October 17, 2018 07:58
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 robpalme/875752a7f4426da2f17a085d286eb7a9 to your computer and use it in GitHub Desktop.
Save robpalme/875752a7f4426da2f17a085d286eb7a9 to your computer and use it in GitHub Desktop.
Compare calling Function() once-per-function vs first concatenating source text into an array of functions
{
function empty () {}
const fnsLength = 10;
const fns = new Array(fnsLength).fill(empty);
const fnStrings = fns.map(x => x.toString());
var ix = 0;
function emptySingle () {
return fns.map(_ => Function(`'use strict';return (function () {}); //${ix++}`)());
}
function uncached () {
return fns.map(x => Function(`'use strict';return (${x.toString()}); //${ix++}`)());
}
var strs;
function cached () {
return fnStrings.map(x => Function(`'use strict';return (${x}); //${ix++}`)());
}
function arrayTogether () {
const fnStrings = fns.map(x => x.toString());
const fnArray = `'use strict';return [(${fnStrings.join('),(')})]; //${ix++}`;
return Function(fnArray)();
}
function emptyTogether () {
const fnStrings = fns.map(x => "(function () {})");
const fnArray = `'use strict';return [${fnStrings.join(',')}]; //${ix++}`;
return Function(fnArray)();
}
const o = {};
const ITERATIONS = 1e2;
function runFn(fn) {
var i=ITERATIONS;
var start = new Date();
while (i--) {
const genFns = fn();
for (const genFn of genFns) {
genFn();
}
}
var dur = new Date() - start;
var numFns = fns.length*ITERATIONS;
console.log(fn.name + " " + dur + "ms / " + (dur * 1000 / numFns) + " us each / " + numFns + " fns");
}
runFn(emptyTogether);
runFn(arrayTogether);
runFn(emptySingle);
runFn(cached);
runFn(uncached);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment