JS iteration and setting vs map cloning (v4)

Revision 4 of this benchmark created on


Description

Just want to verify what method of JS Map cloning is fastest

Setup

let arr = new Array(10000)
for (let i = 0; i < 10000; i++) {
  arr[i] = ['key' + i, 'value' + i]
}
let map = new Map(arr)

/** Copied from obliterator/forEach */
const support = {
	ARRAY_BUFFER_SUPPORT: typeof ArrayBuffer !== 'undefined',
    SYMBOL_SUPPORT: typeof Symbol !== 'undefined'
}


var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT;
var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT;

function forEach(iterable, callback) {
  var iterator, k, i, l, s;

  if (!iterable) throw new Error('obliterator/forEach: invalid iterable.');

  if (typeof callback !== 'function')
    throw new Error('obliterator/forEach: expecting a callback.');

  // The target is an array or a string or function arguments
  if (
    Array.isArray(iterable) ||
    (ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) ||
    typeof iterable === 'string' ||
    iterable.toString() === '[object Arguments]'
  ) {
    for (i = 0, l = iterable.length; i < l; i++) callback(iterable[i], i);
    return;
  }

  // The target has a #.forEach method
  if (typeof iterable.forEach === 'function') {
    iterable.forEach(callback);
    return;
  }

  // The target is iterable
  if (
    SYMBOL_SUPPORT &&
    Symbol.iterator in iterable &&
    typeof iterable.next !== 'function'
  ) {
    iterable = iterable[Symbol.iterator]();
  }

  // The target is an iterator
  if (typeof iterable.next === 'function') {
    iterator = iterable;
    i = 0;

    while (((s = iterator.next()), s.done !== true)) {
      callback(s.value, i);
      i++;
    }

    return;
  }

  // The target is a plain object
  for (k in iterable) {
    if (iterable.hasOwnProperty(k)) {
      callback(iterable[k], k);
    }
  }

  return;
};

Test runner

Ready to run.

Testing in
TestOps/sec
Mnemonist approach
let clone = new Map()

forEach(map, function(value, key) {
  clone.set(key, value);
});
ready
Native for..of
let clone = new Map()

for (let [key, value] of map) {
	clone.set(key, value)
}
ready
Clone from entries
let clone = new Map(map.entries())
ready
Use native map cloning
let clone = new Map(map)
ready

Revisions

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