regex vs. jQuery filter

JavaScript performance comparison

Test case created by Andreas Goebel

Info

This testcase compares the performance of a particular selection of elements. Once using a regular expression and once using jQuery .filter()

Preparation code

<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" id="test" />
 
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" id="P5322311" />
 
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" id="test" />
 
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" id="P113332" />
 
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" id="test" />
 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  jQuery.expr[':'].regex = function(elem, index, match) {
   var matchParams = match[3].split(','),
       validLabels = /^(data|css):/,
       attr = {
     method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
     property: matchParams.shift().replace(validLabels, '')
       },
       regexFlags = 'ig',
       regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
   return regex.test(jQuery(elem)[attr.method](attr.property));
  }
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.filter()
$('img').filter(function() {
 return this.id.charAt(0) === 'P' && !isNaN(this.id.slice(1, 6));
});
pending…
regex
$('img:regex(id, P\d{5,})');
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