Search code examples
javascriptnode.jsdictionaryes6-map

Higher perf - Map.prototype.forEach or for..of?


Say I have:

const m = new Map();

is there a performance difference between:

for(let v of m){

}

vs.

m.forEach(v => {});

I assume Map.protoype.forEach uses an iterator just like for..of? I read here that's it safe to delete keys from the map during iteration using for..of, see: ES6: Is it dangerous to delete elements from Set/Map during Set/Map iteration?

and I am wondering if it's safe to delete keys from the map with a Map.prototype.forEach loop also.


Solution

  • Did a little benchmark with the following code on node.js 8.11

    const Benchmark = require('benchmark');
    const suite = new Benchmark.Suite();
    
    suite
      .add('for of', function () {
        const m = new Map();
        for (let i = 0; i < 100; i++) {
          m.set(`key${i}`, i);
        }
    
        for (let v of m) {
          m.delete(v);
        }
      })
      .add('forEach', function () {
        const m = new Map();
        for (let i = 0; i < 100; i++) {
          m.set(`key${i}`, i);
        }
    
        m.forEach(v => {
          m.delete(v);
        })
      })
      .on('cycle', function (event) {
        console.log(String(event.target));
      })
      .on('complete', function () {
        console.log('Fastest is ' + this.filter('fastest').map('name'));
      })
      // run async
      .run({ 'async': true });
    

    And the result was pretty interesting:

    for of x 88,105 ops/sec ±0.36% (89 runs sampled)
    forEach x 81,532 ops/sec ±0.55% (90 runs sampled)
    Fastest is for of