vendredi 5 janvier 2018

How is the native implementation of the map method so fast?

How is the native implementation of the map method so fast?

I reimplemented it, and it's still around 2 times slower than the .map method called to iterate over an array.

Here's my code:

Array.prototype.toMap = function(cb, ctx) {
  if(typeof cb != 'function') {
    return
  }

  var
    result = [],
    len = this.length

  for(var i = 0; i < len; i++) {
    result.push(cb.call(ctx, this[i], i, this))
  }

  return result
}

I'm testing against the following code:

var
  myArr = [10, 10, 10],
  myObj = {
    addOne: function(n) {
      return n + 1
    }
  }

myArr.toMap(function(value, key, array) {
  return this.addOne(value)
}, myObj) // [11, 11, 11]

Just for comparison, I created another method based on the "official" MDN polyfill (https://mzl.la/2EeddOh). Here are the results:

mdn map polyfill: 0.318ms
my map reimplementation: 0.058ms
built in map: 0.021ms

mdn map polyfill: 0.433ms
my map reimplementation: 0.080ms
built in map: 0.029ms

mdn map polyfill: 0.334ms
my map reimplementation: 0.056ms
built in map: 0.029ms

mdn map polyfill: 0.429ms
my map reimplementation: 0.057ms
built in map: 0.021ms

mdn map polyfill: 0.333ms
my map reimplementation: 0.056ms
built in map: 0.021ms

What are your thoughts?

Aucun commentaire:

Enregistrer un commentaire