jQuery dollar overwrite
JavaScript performance comparison
Info
jQuery selector overwrite as an attempt to get a better performance on simple selections
Preparation code
<div id="firstId">
<div class="testClass">
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(cl, tag) {
var els, matches = [],
i = 0,
len, regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
els = document.getElementsByTagName(tag || "*");
if (!els[0]) return false;
for (els.length; i--;) {
if (els[i].className.match(regex)) {
matches.push(els[i]);
}
}
return matches;
};
}
S = (function($) {
return function(el, tag) {
if (typeof el === 'object') return $(el);
//if (document.querySelectorAll) return document.querySelectorAll(el);
var firstChar = el.charAt(0);
var spaces = new RegExp('\s');
if (!el.match(spaces)) {
switch (firstChar) {
case "#":
return $(document.getElementById(el.slice(1)));
case ".":
return $(document.getElementsByClassName(el.slice(1), tag));
default:
return $(el);
}
}
return $(el);
}
}($));
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
jQuery $ overwrite |
|
pending… |
jQuery without $ overwrite |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments