Indices of letter in string

JavaScript performance comparison

Test case created by Gavin Kistner

Info

See this Stack Overflow question.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var s1 = "scissors",
        s2 = "It's the end of the world as we know it, and I feel fine.";
   
    function tomalak(str, char) {
      return str
             .split("")
             .map(function (c, i) { if (c == char) return i; })
             .filter(function (v) { return v >= 0; });
    }
   
    function phrogzIndexOf(substring,string){
      var a=[],i=-1;
      while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
      return a;
    }
   
    function phrogzLoop(char,str){
      for (var a=[],i=str.length;i--;) if (str[i]==char) a.push(i);
      return a;
    }
   
    function vcsjonesLoop(char,str){
      var indices = [];
      for(var i=0; i<str.length;i++) {
        if (str[i] === char) indices.push(i);
      }
    }
};
</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's Functional
tomalak(s1,"s");
tomalak(s2,"e");
pending…
Phrogz's indexOf
phrogzIndexOf("s",s1);
phrogzIndexOf("e",s2);
pending…
Phrogz's Loop
phrogzLoop("s",s1);
phrogzLoop("e",s2);
pending…
VCSJones' Loop
vcsjonesLoop("s",s1);
vcsjonesLoop("e",s2);
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

Add a comment