Skip to content

Instantly share code, notes, and snippets.

@scarlac
Last active December 2, 2017 11:19
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 scarlac/87dc480c9f5893060a17a4c6f61cbc85 to your computer and use it in GitHub Desktop.
Save scarlac/87dc480c9f5893060a17a4c6f61cbc85 to your computer and use it in GitHub Desktop.
Benchmark comparison of 'clever' prototype trick vs arrow function call
const arr = [
'Duis',
' felis ',
' ex ',
'finibus',
' vitae ',
' tempus ',
' ut ',
'commodo',
' nec ',
' ante. ',
' Quisque ',
' imperdiet ',
' laoreet ',
' dignissim. ',
' Donec ',
' porttitor ',
' feugiat ',
' tortor ',
' et ',
' iaculis. ',
' Nam ',
' volutpat ',
' libero ',
' sit ',
' amet ',
' mattis ',
' pellentesque. ',
' Pellentesque ',
' habitant ',
' morbi ',
' tristique ',
' senectus ',
' et ',
' netus ',
' et ',
' malesuada ',
' fames ',
' ac ',
' turpis ',
' egestas. ',
' Vivamus ',
' venenatis ',
' viverra ',
' justo ',
'quis',
' tincidunt ',
' ex ',
' sagittis ',
' non. ',
' Vestibulum ',
' sollicitudin ',
' vulputate ',
' sem ',
' et ',
' finibus. ',
' Fusce ',
' elit ',
' diam ',
'porta',
' in ',
' nibh ',
' eget ',
'placerat',
' malesuada ',
' sapien. ',
' Suspendisse ',
' dolor ',
' magna ',
'auctor',
' a ',
' ligula ',
' eu ',
'laoreet',
' sodales ',
' nulla. ',
' Proin ',
' vel ',
' nisl ',
' vitae ',
' tellus ',
' tempus ',
' tempor ',
' et ',
' dignissim ',
' metus.'
];
function benchmarkPrototype() {
console.time('Prototype');
for (let i = 0; i < 20000; i++) {
arr.map(Function.prototype.call, String.prototype.trim);
}
console.timeEnd('Prototype');
}
function benchmarkArrowFn() {
console.time('Arrow function');
for (let i = 0; i < 20000; i++) {
arr.map(s => s.trim());
}
console.timeEnd('Arrow function');
}
Math.random() >= .5 ? benchmarkPrototype() : benchmarkArrowFn();
// Results of 18 runs of each:
// https://docs.google.com/spreadsheets/d/1mZx7ENLTeCG0G_AwjCCv71Bc2MYICfvGoyDvHAeOOYY/edit#gid=0
// To test yourself:
// $ for i in `seq 1 50`; do node prototype-vs-arrowfn.js; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment