Created
May 9, 2010 05:07
-
-
Save diogobaeder/394956 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Just some helpers to accelerate jQuery object instantiation, when we are using element IDs or classes as references. | |
It seems stupid, but using these helpers actually boosts the performance a lot. | |
Try the code below on the jQuery homepage, and see the results by yourself (must have Firebug installed) | |
*/ | |
// Helper for getting by ID | |
function $id(id, context) { | |
return $((context || document).getElementById(id)); | |
} | |
// Helper for getting by class name - OK, this helper is a lot better on Firefox, but in Chrome it performs about the same as without it | |
if (document.getElementsByClassName) { | |
function $class(klass, context) { | |
return $((context || document).getElementsByClassName(klass)); | |
} | |
} | |
else { | |
function $class(klass, context) { | |
return $(context || document).find('.' + klass); | |
} | |
} | |
console.log("\n\n\n----------\n"); | |
console.time('ID: without helper'); | |
for (var i = 0; i < 10000; i++) { | |
$("#jq-interior"); | |
} | |
console.timeEnd('ID: without helper'); | |
console.time('ID: with helper'); | |
for (var i = 0; i < 10000; i++) { | |
$id("jq-interior"); | |
} | |
console.timeEnd('ID: with helper'); | |
console.time('ID: native'); | |
for (var i = 0; i < 10000; i++) { | |
document.getElementById("jq-interior"); | |
} | |
console.timeEnd('ID: native'); | |
console.time('Class: without helper'); | |
for (var i = 0; i < 10000; i++) { | |
$(".jq-enhanced"); | |
} | |
console.timeEnd('Class: without helper'); | |
console.time('Class: with helper'); | |
for (var i = 0; i < 10000; i++) { | |
$class("jq-enhanced"); | |
} | |
console.timeEnd('Class: with helper'); | |
console.time('Class: native'); | |
for (var i = 0; i < 10000; i++) { | |
document.getElementsByClassName("jq-enhanced"); | |
} | |
console.timeEnd('Class: native'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment