slice vs map

JavaScript performance comparison

Test case created by kajyr

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const ARRAY_SIZE = 1000;
  
  const list = [...Array(ARRAY_SIZE).keys()].map(id => ({id}));
  
  function applyMap(list, id, fn) {
      return list.map(item => (item.id === id ? fn(item) : item));
  }
  
  function applySlice(list, id, fn) {
      const index = list.findIndex(el => el.id === id);
      if (index < 0) {
          return list;
      }
  
      return [...list.slice(0, index), fn(list[index]), ...list.slice(index + 1)];
  }
  
  function update (elem) {
     return ({...elem, wow: true })
  } 
  
  
  function applyMapFor(list, id, fn) {
      var result = [];
      for (var i = 0; i < list.length; i++) {
          result[i] = list[i].id === id ? fn(list[i]) : list[i];
      }
      return result;
  }

};
</script>

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
applyMapFor
applyMapFor(list, 999, update)
pending…
applyMap with high-index
applyMap(list, 999, update)
pending…
applySlice with high-index
applySlice(list, 999, update)
pending…

Revisions

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

0 Comments