For vs Find vs Filter

JavaScript performance comparison

Test case created by cborchert

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const colors = [
    { color: 'red', value: 'a' },
    { color: 'green', value: 'b' }, // šŸ‘ˆ this one
    { color: 'orange', value: 'c' },
    { color: 'green', value: 'd' },
  ]
  

};
</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
For
// initialize the variable
let value

// loop through the all the colors
for (let i = 0; i < colors.length; i++) {
  if (colors[i].color === 'green') {
    // We have a winner!
    // get the value
    value = colors[i].value
    // break out of the loop... we have our value!
    break
  }
}
pendingā€¦
Filter
// Get an array of objects whose color is green
const selectedColors = colors.filter(({ color }) => color === 'green')
// get the value of the first object, if it exists
const value = selectedColors[0] && selectedColors[0].value
pendingā€¦
Find
// Get the first object that matches
const selectedColor = colors.find(({ color }) => color === 'green')
// get the value of the first object, if it exists
const value = selectedColor && selectedColor.value
pendingā€¦
Find 2
function test(item){
  return item.color === 'green';
}
// Get the first object that matches
const selectedColor = colors.find(({ color }) => color === 'green')
// get the value of the first object, if it exists
const value = selectedColor && selectedColor.value
pendingā€¦
Filter 2
function test(item){
  return item.color === 'green';
}

// Get an array of objects whose color is green
const selectedColors = colors.filter(test)
// get the value of the first object, if it exists
const value = selectedColors[0] && selectedColors[0].value
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