Reduce vs for loop for transformation

Benchmark created on


Setup

let nodeMap = {}
for (let i of Array(1000).keys()) {
  nodeMap[i] = { id: i }
}
const nodeArray = []
const now = new Date().toJSON()
for (let i of Array(1000).keys()) {
  nodeArray.push({ id: i, updated: now })
}

Test runner

Ready to run.

Testing in
TestOps/sec
Current method with reduce and spread operators
// Iterates and transforms the incoming nodeArray to a hash/dict
const updated = nodeArray.reduce(
  (result, current) => ({
    // copies the hash/dict
    ...result,
    // adds the incoming node to the hash/dict
    [current.id]: {
      // looks up and copies the existing node
      ...nodeMap[current.id],
      // copies the incoming node
      ...current,
    },
  }),
  {},
);
// Iterates and transforms the incoming nodeArray again to return just the values of the hash/dict
const updatedLength = Object.values(updated).length;
// Iterates and copies the incoming nodeHash/Dict to merge in to the existing nodeMap
nodeMap = { ...nodeMap, ...updated };
ready
Traditional for loop
// Set up scoped vars for holding values in between iterations and for the bulkPut after
let incomingNode, existingNode, updatedNodes = []
// Begin iterating the incoming nodeArray
for (let i = 0, len = nodeArray.length; i < len; i++) {
  // gets the incomingNode
  incomingNode = nodeArray[i]
  // Looks up and copies the existing node the incomingNode is updating and merges the incomingNode with it
  updatedNode = { ...nodeMap[incomingNode.id], ...incomingNode }
  // Update the nodeMap with the updatedNode
  nodeMap[updatedNode.id] = updatedNode
  // Stash the updated node for the dexie call after we're done
  updatedNodes.push(updatedNode)
}
const updatedLength = updatedNodes.length;
ready

Revisions

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