query str parsing: regex vs split

JavaScript performance comparison

Revision 9 of this test case created

Info

[Pocket Margin] per [Sold-to Party: City], [Calendar Year] filtered by [Sold-To Party]="Zweig AG", "Zweig GmbH", [Calendar Year]="2012" (Margin Decomposition)

Preparation code

<script>
  var query = 'http://your.domain/product.aspx?category=4&product_id=2140&query=lcd+tv';

  function split() {
    var queryString = {};
    query.split("?").pop().split("&").forEach(function(prop) {
      var item = prop.split("=");
      queryString[item[0]] = item[1];
    });
    return queryString;
  }

  function splitFor() {
    var queryString = {},
        parts = query.split("?").pop().split("&"),
        i = 0,
        l = parts.length,
        item;

    for (; i < l; i++) {
      item = parts[i].split("=");
      queryString[item[0]] = item[1];
    }
    return queryString;
  }

  function splitI(s, chars) {
    var r = [];
    var index = 0;
    var i = 0;
    var soFar = 0;
    for (; s[i]; i++) {
      if (chars.length == 1) {
        if (s[i] == chars) {
          r.push(s.substr(index, i - index));
          index = i + 1;
        }
      } else {
        //if (s[i] == chars[soFar]) {
        //}
      }
    }

    if (i > index) {
      r.push(s.substr(index, i - index));
    }

    return r;
  }

  function splitIndex() {
    var queryString = {},
        parts = splitI(splitI(query, "?")[0], "&"),
        i = 0,
        l = parts.length,
        item;

    for (; i < l; i++) {
      item = splitI(parts[i], "=");
      queryString[item[0]] = item[1];
    }
    return queryString;
  }

  function regex() {
    var queryString = {};
    query.replace(/(\[.*\])? per (\[.*\])? filtered by (\[.*")? \((.*)\)$/i, function($0, $1, $2, $3) {
      queryString[$1] = $3;
    });

    return queryString;
  }
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
regex
regex()
pending…
split
split()
pending…
split with for loop
splitFor()
pending…
split with index
splitIndex()
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment