Using ?: in regex capture groups

JavaScript performance comparison

Test case created by q--

Info

A demonstration why it's faster to use ?: at the beginning of RegEx capture groups that match unused data.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ234567890_-';
   
    /**
        @name rand
        @param min - the minimum random number to return
        @param max - the maximum random number to return
        @description returns a random number between @param min and @param max 
    */

    function rand(min,max){
        var max=max-min;
        return Math.floor(Math.random()*(max+1))+min;
    }
   
   
    function getRandomStr(length){
        var str='';
        if(!length) length=rand(5,36);
       
       
        for(var i=0;i<length;i++){
                str+=chars[rand(0,chars.length-1)];
        }
       
        return str;
    }
   
    //Generate test object
    var testObj={},
   
    i=10000;
    while(i--){
       testObj[getRandomStr(1000)]='';
    }
};
</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
Test without ?: at the beginning of capture groups
for(i in testObj){
   i.match(/^.([a-z]|[0-9])(\d+)?_?([\w]{1,3})(.+)/i);
}
pending…
Test with ?: at the beginning of capture groups
for(i in testObj){
   i.match(/^.(?:[a-z]|[0-9])(?:\d+)?_?(?:[\w]{1,3})(?:.+)/i);
}
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