Skip to content

Instantly share code, notes, and snippets.

@jed
Created January 5, 2011 22:21
Show Gist options
  • Save jed/767139 to your computer and use it in GitHub Desktop.
Save jed/767139 to your computer and use it in GitHub Desktop.
a javascript include that uses the DOM to test 4 guid schemes
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" )
}
@jed
Copy link
Author

jed commented Jan 5, 2011

to try this on an arbitrary dom, paste this into the location field of any web page:

javascript:with(document)(body.appendChild(createElement('script')).src='https://gist.github.com/raw/767139/73c9ddadd4da9f65ee9b53340a6127f700ff459b/guids.js')._

my results for chrome on the phildelphia craigslist front page are usually as follows:

expando index: 1ms
expando lookup: 0ms
bucketless index: 62ms
bucketless lookup: 58ms
bucket integers index: 18ms
bucket integers lookup: 28ms
bucket strings index: 22ms
bucket strings lookup: 16ms

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment