arr-vs-map-1234

JavaScript performance comparison

Test case created by hallcyon11

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const arr = Array.from({length: 10000}, () => Math.floor(Math.random() * 40))
  const target = 6
  const set = new Set(arr)
  

};
</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
Array
// O(N)2
const a = () => {
  for (let i = 0; i < arr.length; i++) {
    const I = arr[i]
    for (let j = 0; j < arr.length; j++) {
      const J = arr[j]
      const required = target - I
      if (required === J) {
        if (i === j) continue
        return [i, j]
      }
    }
  }
}

const A = a()
console.log(A)
pending…
Set
// O(N)
const b = () => {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i]
    const required = target - item
    
    if (set.has(required)) {
      const requiredIndex = arr.indexOf(required)
      if (requiredIndex === i) continue
      return [i, requiredIndex]
    }
  }
}

const B = b()
console.log(B)
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