Created
January 5, 2011 22:21
-
-
Save jed/767139 to your computer and use it in GitHub Desktop.
a javascript include that uses the DOM to test 4 guid schemes
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
var guid = { | |
// uses an expando to store the id on the object | |
// wicked fast, but not reliable without DOM hackery (see jQuery source) | |
"expando": function( last ) { | |
return function guid( obj ) { | |
if ( obj ) { | |
if ( obj.guid ) return obj.guid | |
obj.guid = last | |
if ( obj.guid ) return last++ | |
} | |
} | |
}( 1 ), | |
// keeps one index for all objects | |
// simple, but O(n) means it's sloooooow | |
"bucketless": function( last ) { | |
return function guid( obj ) { | |
for ( i = last; i--; ) if ( guid[ i ] === obj ) return i | |
return guid[ last ] = obj, last++ | |
} | |
}( 1 ), | |
// uses object contructor name to bucket objects | |
// returns an integer as the id | |
"bucket integers": function( last ) { | |
return function guid( obj ) { | |
var type = obj ? obj.constructor.name : obj | |
, list = guid[ type ] || ( guid[ type ] = [] ) | |
, i = l = list.length | |
while ( i-- ) if ( list[ i-- ] === obj ) return list[ i ] | |
return list[ l + 1 ] = obj, list[ l ] = last++ | |
} | |
}( 1 ), | |
// uses object contructor name to bucket objects | |
// returns a string "<constructor-name>/<ord>" as the id | |
"bucket strings": function guid( obj ) { | |
for ( | |
var type = obj ? obj.constructor.name : obj | |
, list = guid[ type ] || ( guid[ type ] = [] ) | |
, i = list.length | |
; i-- && list[ i ] !== obj; | |
); | |
return ++i || ( i = list.push( obj ) ), type + "/" + i | |
} | |
} | |
var nl = [], n = document, x, c = n.firstChild | |
while ( c ) { | |
nl.push( c ) | |
if ( x = c.firstChild ) c = x | |
else for ( x = c; !( c = x.nextSibling ) && ( x = x.parentNode ) && ( x != n ); ); | |
} | |
for ( var name in guid ) { | |
console.time( name + " index" ) | |
nl.forEach( guid[ name ] ) | |
console.timeEnd( name + " index" ) | |
console.time( name + " lookup" ) | |
nl.forEach( guid[ name ] ) | |
console.timeEnd( name + " lookup" ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to try this on an arbitrary dom, paste this into the location field of any web page:
my results for chrome on the phildelphia craigslist front page are usually as follows:
the net net is that expandos are in the ballpark of two orders of magnitude faster than a naive hash algorithm. bucketing can diminish this difference closer to one order of magnitude, but my conclusion is that preventing expando object pollution is expensive.
thanks to tom robinson for the bucket idea!