unique

JavaScript performance comparison

Test case created by demiazz

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function split(length, ratio) {
    const bigger = Math.floor(length * ratio);
    const smaller = length - bigger;
    
    return [smaller, bigger];
  }
  
  function shuffle(xs) {
    for (let i = xs.length; i > 0; i -= 1) {
      const j = Math.floor(Math.random() * (i + 1));
      
      [xs[i], xs[j]] = [xs[j], xs[i]];
    }
  }
  
  function createNumbersSample(length, ratio = 0.75) {
    const [smaller, bigger] = split(length, ratio);
    const result = [];
    
    for (let i = 0; i < bigger; i += 1) {
      result.push(i);
    }
    
    shuffle(result);
    
    for (let i = 0; i < smaller; i += 1) {
      result.push(result[i]);
    }
    
    shuffle(result);
    
    return result;
  }
  
  let sample = createNumbersSample(1000);
  
  function imperative(xs) {
    const result = [];
    const hash = {};
  
    for (let i = 0; i < xs.length; i += 1) {
      const x = xs[i];
  
      if (!hash.hasOwnProperty(x)) {
        result.push(x);
  
        hash[x] = true;
      }
    }
  
    return result;
  }
  
  function imperativeUnsafe(xs) {
    const result = [];
    const hash = {};
  
    for (let i = 0; i < xs.length; i += 1) {
      const x = xs[i];
  
      if (!hash[x]) {
        result.push(x);
  
        hash[x] = true;
      }
    }
  
    return result;
  }
  
  function imperativeMap(xs) {
    const result = [];
    const hash = new Map();
  
    for (let i = 0; i < xs.length; i += 1) {
      const x = xs[i];
  
      if (!hash.has(x)) {
        result.push(x);
  
        hash.set(x, true);
      }
    }
  
    return result;
  }
  
  function imperativeSet(xs) {
    const set = new Set(xs);
  
    return Array.from(set);
  }
  
  function predicate(x, index, list) {
    return list.indexOf(x) === index;
  }
  
  function declarative(xs) {
    return xs.filter(predicate);
  }

};

Benchmark.prototype.teardown = function() {
  sample = createNumbersSample(1000);

};
</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
imperative
imperative(sample);
pending…
imperative / Set
imperativeSet(sample);
pending…
imperative / unsafe
imperativeUnsafe(sample);
pending…
imperative / Map
imperativeMap(sample);
pending…
declarative
declarative(sample);
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