jquery data selectors

Benchmark created on


Preparation HTML

<div id="blueprintList">
<div class="blueprint floor-0 building-A" data-floor="0" data-building="A">0-A</div>
<div class="blueprint floor-0 building-B" data-floor="0" data-building="B">0-B</div>
<div class="blueprint floor-0 building-C" data-floor="0" data-building="C">0-C</div>
<div class="blueprint floor-0 building-D ui-clicked" data-floor="0" data-building="D">0-D</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var $blueprintList = $("#blueprintList");
  var $blueprints = $blueprintList.children(".blueprint");
  var $t = $blueprints.children(".ui-clicked");
  
  (function() {
  
   var matcher = /\s*(?:((?:(?:\\\.|[^.,])+\.?)+)\s*([!~><=]=|[><])\s*("|')?((?:\\\3|.)*?)\3|(.+?))\s*(?:,|$)/g;
  
   function resolve(element, data) {
  
    data = data.match(/(?:\\\.|[^.])+(?=\.|$)/g);
  
    var cur = jQuery.data(element)[data.shift()];
  
    while (cur && data[0]) {
     cur = cur[data.shift()];
    }
  
    return cur || undefined;
  
   }
  
   jQuery.expr[':'].data = function(el, i, match) {
  
    matcher.lastIndex = 0;
  
    var expr = match[3],
        m, check, val, allMatch = null,
        foundMatch = false;
  
    while (m = matcher.exec(expr)) {
  
     check = m[4];
     val = resolve(el, m[1] || m[5]);
  
     switch (m[2]) {
     case '==':
      foundMatch = val == check;
      break;
     case '!=':
      foundMatch = val != check;
      break;
     case '<=':
      foundMatch = val <= check;
      break;
     case '>=':
      foundMatch = val >= check;
      break;
     case '~=':
      foundMatch = RegExp(check).test(val);
      break;
     case '>':
      foundMatch = val > check;
      break;
     case '<':
      foundMatch = val < check;
      break;
     default:
      if (m[5]) foundMatch = !! val;
     }
  
     allMatch = allMatch === null ? foundMatch : allMatch && foundMatch;
  
    }
  
    return allMatch;
  
   };
  
  }());
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
class selector
var floor = $t.data("floor");
var building = $t.data("building");
$blueprints.filter(".floor-0.building-A");
ready
attribute selector
var floor = $t.data("floor");
var building = $t.data("building");
$blueprints.filter("[data-floor=0][data-building=A]");
ready
data selector
var floor = $t.data("floor");
var building = $t.data("building");
$blueprints.filter(":data(floor==0,building==A)");
ready

Revisions

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