document.all[id]
is completely different to document.IDElements[id]
and its a LIVE HTMLCollection
so I’m not suprised that document.getElementById(id)
is way faster (which AFIK is also optimized).
Which I didn’t even say that document.all
is faster.
What’s faster is having reference to the Element already:
var el = document.getElementById('theElement');
function foo() {
return document.getElementById('theElement');
}
function foo2() {
return el;
}
Which one you think would be faster? In this above example, the difference probably aren’t even measurable. This is too simple of an example, the point is having reference to a value is always faster than getting the value again.
Just like how when we use a for loop
:
var arr = [1000000000000x length] // an array with a length of: 1000000000000
for(var i = 0; i < arr.length; i++) {..}
Over:
for(var i = 0, l = arr.length; i < l; i++) {...}
I’m sure we all know that the second one is much faster and performant, and recommended, and its caching the value, so I still stand clear with my statement.
You want a jQuery
example too??
$('div').css('color', 'red');
$('div').css('background', 'black');
Over:
var divs = $('div');
divs.css('color', 'red');
divs.css('background', 'black');
And yes I’m aware I can do:
$('div').css({ color: 'red', background: 'black'});
// or
$('div').css('color', 'red').css('background', 'black');