array-chains

JavaScript performance comparison

Test case created by thoughtspile

Preparation code

<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
<script>
// Loading `lodash.fp.js` converts `_` to its fp variant.
_.defaults({ 'a': 2, 'b': 2 })({ 'a': 1 });
// ➜ { 'a': 1, 'b': 2 }

// Use `noConflict` to restore the pre-fp variant.
var fp = _.noConflict();

_.defaults({ 'a': 1 }, { 'a': 2, 'b': 2 });
// ➜ { 'a': 1, 'b': 2 }
fp.defaults({ 'a': 2, 'b': 2 })({ 'a': 1 });
// ➜ { 'a': 1, 'b': 2 }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  const arr = Array(1100).fill({})
    .map(e => Math.random() > 0.1
      ? { user: { wealth: Math.random() * 1000 } }
      : null);

};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Chain
const res = arr
  .filter(e => e && e.user)
  .map(e => e.user)
  .map(u => u.wealth || 0)
  .reduce((acc, wealth) => acc + wealth, 0);
pending…
No-chain
const res = arr.reduce((acc, e) => {
  const wealth = (e && e.user) ? (e.user.wealth || 0) : 0;
  return acc + wealth;
}, 0);
pending…
For-of
let w = 0;
for (let e of arr) {
  if (e && e.user) {
    w += e.user.wealth || 0;
  }
}
pending…
For index
let w2 = 0;
for (let i = 0; i < arr.length; i++) {
  const e = arr[i];
  if (e && e.user) {
    w2 += e.user.wealth || 0;
  }
}
pending…
Lodash chain
const res = _.chain(arr)
  .filter(e => e && e.user)
  .map(e => e.user)
  .map(u => u.wealth || 0)
  .reduce((acc, wealth) => acc + wealth, 0);
pending…
Lodash-fp chain
fp.flow(
  fp.filter(e => e && e.user),
  fp.map(e => e.user),
  fp.map(u => u.wealth || 0),
  fp.reduce((acc, wealth) => acc + wealth, 0)
)(arr);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments