Josh, that's all very true, but the reason that getElementById() is faster
than getElementsByTagName() for example, is that it doesn't traverse the DOM
to perform a string comparison of each element's ID.

I don't know what the exact mechanism is, but I would assume it is a hash
table from element IDs to the DOM nodes - that would seem the most sensible,
although could obviously vary between browsers.

As to why a longer ID would result in slower lookups, that's an odd one. If
it is a hash table then the hashing algorithm would technically take longer
for a longer string, but I can't imagine it being noticeable unless it was
really appalling!

Just my £0.02 worth
--rob


On 6/22/07, Josh Bush <[EMAIL PROTECTED]> wrote:


I can only imagine the longer the attribute, the longer the comparison
will take.
<Puts on CompSci hat>

String comparison has to compare each char at each position.
"abc"="abc" would involve 3 iterations.

"digitalbush.com"="digitalbush.com" would involve 15 iterations.

In the description at the top with "aXXXX, another with
ids like ааааааааааааааааааааааааааааааааХХХХ," if every element is
preceeded by 32 "a"'s, then looking for
"ааааааааааааааааааааааааааааааааYYYY" would result in 32 iterations
before it failed to match that attribute.  If the document has 100
elements all with 32 a's as a prefix, then worst case scenario is (100
x 32) + 4 [the actual remaining "YYYY"] would yield 3,204 comparisons.

Please keep in mind, we are talking about tiny cpu time, but that
could add up over a large document.

-Josh

On Jun 22, 10:38 am, Su <[EMAIL PROTECTED]> wrote:
> Weird. It'd provide an interesting guideline if there's an id-length
> threshold where that slowdown kicks in.
>
> On 6/22/07, John Resig <[EMAIL PROTECTED]> wrote:
>
>
>
> > Dimitii -
>
> > Those results are really interesting - you should post them to the
jQuery
> > Dev list (where we discuss issues like selector speed).
>
> > More information about the list can be found here:
> >http://docs.jquery.com/Discussion




--
Rob Desbois
Eml: [EMAIL PROTECTED]
Tel: 01452 760631
Mob: 07946 705987
"There's a whale there's a whale there's a whale fish" he cried, and the
whale was in full view.
...Then ooh welcome. Ahhh. Ooh mug welcome.

Reply via email to