Array filter - grep vs map vs each vs for

Benchmark created by Mark Stewart on


Description

Comparing speed and efficiency of looking for certain values in array by different methods.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script>
var questions = [
            {
                "answerString": "Yes",
                "text": 1510
            },{
                "answerString": "No",
                "text": 1511
            },{
                "answerString": "45",
                "text": 2227
            },{
                "answerString": "Female",
                "text": 2228
            },{
                "answerString": "Yes",
                "text": 1510
            },{
                "answerString": true,
                "text": 3514
            },{
                "answerString": false,
                "text": 3545
            }

        ];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Grep
$(document).ready(function() {
  var grepGender;
  var grepAge;
  $.grep(questions, function(e, val) {
    if (e.text === 2228) {
      grepGender = e.answerString;
    } else if (e.text === 2227) {
      grepAge = e.answerString;
    }
  });
});
ready
Map
$(document).ready(function() {
  var arrGender;
  var arrAge;
  $.map(questions, function(o) {
    if (o["text"] === 2228) {
      arrGender = o.answerString.toString();
    } else if (o["text"] === 2227) {
      arrAge = o.answerString.toString();
    }
  });
});
ready
Each
$(document).ready(function() {
  var eachGender;
  var eachAge;
  $.each(questions, function(key, val) {
    if (val.text === 2228) {
      eachGender = val.answerString;
    } else if (val.text === 2227) {
      eachAge = val.answerString;
    }
  });
});
ready
For
$(document).ready(function() {
  var forGender;
  var forAge;
  for (var i = 0; i < questions.length; i++) {
    if (questions[i].text === 2228) {
      forGender = questions[i].answerString;
    } else if (questions[i].text === 2227) {
      forAge = questions[i].answerString;
    }
  }
});
ready
ForIn
$(document).ready(function() {
  var forInGender;
  var forInAge;
  for (var j in questions) {
    if (questions[j].text === 2228) {
      forInGender = questions[j].answerString;
    } else if (questions[j].text === 2227) {
      forInAge = questions[j].answerString;
    }
  }

});
ready

Revisions

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

  • Revision 1: published by Mark Stewart on
  • Revision 2: published by Emilian Gospodinov on