query str parsing: regex vs split (v5)

Revision 5 of this benchmark created by Pascal on


Description

http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/

Preparation HTML

<script>
  var query = 'category=4&product_id=2140&query=lcd+tv&hello=world';

  function regex() {
    var queryString = {};
    query.replace(/([^?=&]+)(=([^&]*))?/g, function ($0, $1, $2, $3) {
      queryString[$1] = $3;
    });
  
    return queryString;
  }

  function splitWhile() {
      var i, item, parts, result;
      if (query == null) query = "";
      result = {};
      parts = query.split("&");
      i = parts.length;
      while (i--) {
        item = parts[i].split("=");
        result[item[0]] = item[1];
      }
      return result;
  };

  function splitFor() {
      var item, parts, result, _i, _len;
      if (query == null) query = "";
      result = {};
      parts = query.split("&");
      for (_i = 0, _len = parts.length; _i < _len; _i++) {
        item = parts[_i];
        item = item.split("=");
        result[item[0]] = item[1];
      }
      return result;
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
regex
regex()
ready
split with for loop
splitFor()
ready
split with while loop
splitWhile()
ready

Revisions

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