Side navigation
#1316 closed enhancement (fixed)
Opened June 22, 2007 03:34PM UTC
Closed August 21, 2007 08:25AM UTC
Last modified August 21, 2007 08:25AM UTC
[Patch] Significantly speed up $('#id')
Reported by: | Chainfire | Owned by: | john |
---|---|---|---|
Priority: | minor | Milestone: | 1.1.4 |
Component: | core | Version: | 1.1.3 |
Keywords: | optimization | Cc: | |
Blocked by: | Blocking: |
Description
$('#id') is significantly slower than $(document.getElementById('id')) . Ofcourse using jQuery should give a small performance hit, but in some cases it can be as much as 40x slower. As discussed in the IRC channel, $('#id') is used a lot, this special often-used case warrants optimization.
Result of this patch, $('#id') is about 10% slower than $(document.getElementById('id')) as opposed to the earlier 4000%.
jQuery.js: jQuery.fn.init (line 165 in 1.1.3a)
// Handle HTML strings if ( typeof a == "string" ) { // HANDLE: $(html) -> $(array) var m = /^[^<]*(<(.|\\s)+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); // HANDLE: $(expr) else { if (!c && /^#[A-Za-z0-9_]+$/.test(a) && (elm = document.getElementById(a.substring(1)))) { a = elm; } else { return new jQuery( c ).find( a ); } } }
Attachments (0)
Change History (4)
Changed June 22, 2007 06:10PM UTC by comment:1
Changed August 21, 2007 07:15AM UTC by comment:2
owner: | → john |
---|
Changed August 21, 2007 08:25AM UTC by comment:3
milestone: | 1.1.3 → 1.1.4 |
---|---|
resolution: | → fixed |
status: | new → closed |
version: | 1.1.2 → 1.1.3 |
Fixed in SVN rev [2821].
Changed August 21, 2007 08:25AM UTC by comment:4
Demo page can be found here:
I managed to write a version that compresses itself a bit more and includes even - and : as valid chars for the id. Compressed, the code is 49 bytes longer than jQuery 1.1.3a (a bit too much but I'm not able to make it better)
The regex, if successful, will return a not null
when one passes an html string or a not null when one passes in id selector.However, the fast id selector can be used only when there's no valid context, so
verify both the cases.If the id case is true,
will avoid to store a null value just in case getElementById does not find the desired element.