indexOf or regex

JavaScript performance comparison

Test case created

Info

Determining whether there's some string in another string - which is better?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var bigOldStringToTest = "ntuahlrceothunhnaeohutnaheontmjsnthskmq;snhksnt;heontmasntoehunstahtheosntuhtmkjrcrakmrlmeorcauhmrc.,jmercahuorcjkbhaurckhaeorckacp.,krmacp.bhrc.abimorc.ubeomjrackbme.rcjhar.,cuheorcahrcuhra.,cmjlchasnteohsnatjmsnohues;rcho.rcomurc;ao.hp0932gh4843chymasntom;l8roe.hplrcpj gmj'''98mauul'a8g. .8aug;lrc ;cg lagl.,. gla8,ggp9a8;hpu s;hob;kmkvwbqdkllbu;vmantoeumm ;mteha. aht;vteuhscuasnh.r,pchuasnthu;snto.hplrca,.amsucuohrs;tceouha/r.,usa .unthlua c.ogrca,.gprcah.usach.,pr rahscehu sancsrua houcah ocuehaso hueocuah oeusca .ourcahounasthsecnal.,ht nuah nhuheontahoeu scansnthoercuh accoeruchsaoceunhns ach chsanteoh crohasuntoueha ehaschoesuntha h scahoteu htoahosntueh ntashsotue as sontheunahoeusntahosecnuthsam.uasorceh usc";
   
    function checkWithIndexOf( str, checkFor ) {
        return str.indexOf( checkFor ) !== -1;
    }
   
    function checkWithRegex( str, checkFor ) {
        return str.match( new RegExp( checkFor ) );
    }
};
</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
indexOf
// This one is definitely in there, somewhere in the middle
checkWithIndexOf( bigOldStringToTest, 'scans' );

// This one is definitely not in there - use capital letters
checkWithIndexOf( bigOldStringToTest, 'AOEU' );

// This one is in there at the beginning
checkWithIndexOf( bigOldStringToTest, 'ntuahl' );

// This one is at the very end
checkWithIndexOf( bigOldStringToTest, 'uasorceh usc' );
pending…
Regex
// This one is definitely in there, somewhere in the middle
checkWithRegex( bigOldStringToTest, 'scans' );

// This one is definitely not in there - use capital letters
checkWithRegex( bigOldStringToTest, 'AOEU' );

// This one is in there at the beginning
checkWithRegex( bigOldStringToTest, 'ntuahl' );

// This one is at the very end
checkWithRegex( bigOldStringToTest, 'uasorceh usc' );
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