uniquevs

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var mkMixedArr = function(len, dev) {
        var xs = new Array(len);
        for (var i = 0; i < len; ++i) {
            var t = Math.floor(Math.random() * dev);
            xs[i] = Math.random() > 0.5 ? t : String(t);
        }
        return xs;
    };
   
    var origin = mkMixedArr(100)
   
    function uniq1(arr) {
      var res = [], item
      for (var i = 0, l = arr.length; i < l; i++) {
        item = arr[i]
        if (arr.indexOf(item) === -1) {
          res.push(item)
        }
      }
      return res
    }
   
    function uniq2(arr) {
      var obj = {}
      arr.forEach(function(item) {
        obj[item] = 1
      })
      return Object.keys(obj)
    }
   
    function uniq3(arr) {
      var hash = [], res = [], item
      for (var i = 0, l = arr.length; i < l; i++) {
        item = arr[i] + ''
        if (hash[item] !== 1) {
          res.push(item)
          hash[item] = 1
        }
      }
      return res
    }
   
    function isObject(obj) {
      return obj === Object(obj)
    }
     
    var idCounter = 0
    function getUid() {
      var id = ++idCounter + ''
      return id
    }
     
    var hasOwnProperty = Object.prototype.hasOwnProperty
     
     
    function uniq4(arr) {
      var returnArray = arr
        , seen = {}
        , cursorInsert = 0
        , cursorRead = 0
        , len = arr.length
       
      while(cursorRead < len) {
        var current = arr[cursorRead++]
        var key = isObject(current) ?
            'o' + getUid(current) :
            (typeof current).charAt(0) + current
     
        if (!hasOwnProperty.call(seen, key)) {
          seen[key] = true
          returnArray[cursorInsert++] = current
        }
      }
      returnArray.length = cursorInsert
      return returnArray
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
indexof
uniq1(origin)
pending…
keys
uniq2(origin)
pending…
hash
uniq3(origin)
pending…
closure
uniq4(origin)
pending…

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

Compare results of other browsers

0 comments

Add a comment