views:

101

answers:

3

document.getElementsByTagName('a').item(0)

and

document.getElementsByTagName('a')[0]

will return the same result...

Is the former faster than the latter, maybe someone knows of test results?

+1  A: 

Selfmade performance test: http://jsfiddle.net/438jh/2/

The difference seems to be negligible. The second method performs better in most case, but if you have a look on how often the loop is performed it does not really matter.

Chrome:

  1. method: ~260ms
  2. method: ~170ms
Felix Kling
Trying your jsFiddle in Firefox 3.6.6, I get about 250 for the first method and 475 for the second.
Daniel Vandersluis
results in ie8: test1: 5000+ test2: ~2000. I even have to punch "no" when IE asks me to stop running scripts during test 2 and it's still significantly faster.
lincolnk
@Daniel: in Firefox 3.6.8. I get ~640 and ~460....
Felix Kling
A: 

item function is a member of NodeList DOM object. NodeLists are array-like but they are not real arrays (e.g.: they are live, read-only, lack of array functions).

The performance difference should be negligible.

galambalazs
Yeap, I read this before posting... http://www.nczonline.net/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/
Alexander
i suggest that you focus on more important optimizations.
galambalazs
A: 

For a more practical example, this technique has the best performance. Look at work by Nicholas Zakas, YAHOO! for more examples:

var cachedDOMquery = Array.prototype.slice.apply(document.getElementsByTagName('a')),
i = cachedDOMquery.length,
item;
while(i--){
    item = cachedDOMquery[i];
    alert(item.href);
}
AutoSponge