Skip to content

Instantly share code, notes, and snippets.

@loz
Last active August 29, 2015 13:56
Show Gist options
  • Save loz/9072117 to your computer and use it in GitHub Desktop.
Save loz/9072117 to your computer and use it in GitHub Desktop.
Exploring speedier finds and querySelectorAll craziness
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.0.min.js"></script>
</head>
<body>
<div id="top"></div>
<div id="results"></div>
<script>
var $domElements = $("<div style='height:400px; overflow:scroll;'></div>");
for(var a = 1; a <= 10; a++) {
var $node = $("<div class='h1'><h1>Section " + a + "</h1></div>")
for(var b = 1; b <= 10; b++) {
var $bnode = $("<div class='h2'><h2>Subsection " + b + "</h2></div>");
for(var c = 1; c <= 100; c++) {
$bnode.append("<p>one</p><p>two</p><p><span><input><div><input></div></span></p>");
}
$node.append($bnode);
}
$domElements.append($node);
}
$("#top").append($domElements);
$results = $("#results");
function benchmark(op, func) {
before = window.performance.now();
nodes = func();
after = window.performance.now();
time = after - before;
$results.append("<p>" + op + ": " + nodes + " nodes in " + time + " seconds</p>");
}
function saneSelectorAll(node, selector) {
prefixed = selector;
cur = node;
docType = document.nodeType;
do {
prefixed = cur.nodeName + ' ' + prefixed;
cur = cur.parentNode;
} while(cur.nodeType != docType);
return node.querySelectorAll(prefixed);
};
h2section = document.querySelectorAll('.h1 .h2')[0];
window.section = h2section;
benchmark("querySelectorAll('input')", function() {
return h2section.querySelectorAll('input').length;
});
benchmark("$.find('input')", function() {
return $(h2section).find('input').length;
});
benchmark("saneSelectorAll('input')", function() {
return saneSelectorAll(h2section,'input').length;
});
benchmark("querySelectorAll('div input')", function() {
return h2section.querySelectorAll('div input').length;
});
benchmark("$.find('div input')", function() {
return $(h2section).find('div input').length;
});
benchmark("saneSelectorAll('div input')", function() {
return saneSelectorAll(h2section,'div input').length;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment