JavaScript string character finder

JavaScript performance comparison

Revision 2 of this test case created

Info

finds the positions of a certain character in a string

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var string = "scissors";
    var char = "s";
   
    function Tomalak(str, char) {
      return str.split("").map(function(c, i) {
        if (c == char) return i;
      }).filter(function(v) {
        return v >= 0;
      });
    }
   
    function Phrogz(string, substring) {
      var a = [],
          i = -1;
      while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
      return a;
    }
   
    function Phrogz2(string, substring) {
      for (var a = [], i = string.length; i--;) if (string[i] == substring) a.push(i);
      return a.reverse();
    }
   
    function Phrogz2Ajax333221Suggestion(string, substring) {
      for (var a = [], i = string.length; i--;) if (string[i] == substring) a.unshift(i);
      return a;
    }
   
    function vcsjones(str, char) {
      var indices = [];
      for (var i = 0; i < str.length; i++) {
        if (str[i] === "s") indices.push(i);
      }
      return indices;
    }
};
</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
Tomalak
var result = Tomalak(string, char);
pending…
Phrogz
var result = Phrogz(string, char);
pending…
vcsjones
var result = vcsjones(string, char);
pending…
Phrogz2
var result = Phrogz2(string, char);
pending…
Phrogz2Ajax333221 Suggestion
var result = Phrogz2Ajax333221Suggestion(string, char);
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