sizzle attr vs qwery attr

Benchmark created by Timmy Willison on


Description

Sizzle uses a long ternary, while qwery constructs a regex and stores it in a cache in case it is used again.

Preparation HTML

<script>
  var cleanCache = {},
      specialChars = /([.*+?\^=!:${}()|\[\]\/\\])/g;
  
  function clean( s ) {
        return cleanCache[ s ] || ( cleanCache[ s ] = s.replace(specialChars, '\\$1') );
  }
  
  function sizzleAttr( qualify, actual, val ) {
  
  return qualify === "=" ?
        actual === val :
        qualify === "^=" ?
        actual.indexOf( val ) === 0 :
        qualify === "$=" ?
        actual.substr(actual.length - val.length) === val :
        qualify === "*=" ?
        actual.indexOf( val ) >= 0 :
        qualify === "~=" ?
        (" " + actual + " ").indexOf( val ) >= 0 :
        qualify === "|=" ?
        actual === val || actual.substr(0, val.length + 1) === val + "-" :
        0;
  }
  
  function cache() {
        this.c = {};
  }
  cache.prototype = {
        g: function( k ) {
                return this.c[k] || undefined;
        },
        s: function( k, v ) {
                this.c[k] = v;
                return v;
        }
  };
  var attrCache  = new cache();
  
  function qweryAttr( qualify, actual, val ) {
        switch ( qualify ) {
        case '=':
                return actual === val;
        case '^=':
                return actual.match( attrCache.g('^=' + val ) || attrCache.s('^=' + val, new RegExp('^' + clean( val ))));
        case '$=':
                return actual.match( attrCache.g('$=' + val ) || attrCache.s('$=' + val, new RegExp( clean( val ) + '$')));
        case '*=':
                return actual.match( attrCache.g( val ) || attrCache.s( val, new RegExp( clean( val ))));
        case '~=':
                return actual.match( attrCache.g('~=' + val ) || attrCache.s('~=' + val, new RegExp('(?:^|\\s+)' + clean( val ) + '(?:\\s+|$)')));
        case '|=':
                return actual.match( attrCache.g('|=' + val ) || attrCache.s('|=' + val, new RegExp('^' + clean( val ) + '(-|$)')));
        }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
sizzle attr (ternary)
sizzleAttr('|=', 'asdfasdf', 'asdfasdf-');
ready
qwery attr (regex)
qweryAttr('|=', 'asdfasdf', 'asdfasdf-');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Timmy Willison on