Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster access an javascript array directly?

I was reading an article: Optimizing JavaScript for Execution Speed

And there is a section that says:

Use this code:

for (var i = 0; (p = document.getElementsByTagName("P")[i]); i++)

Instead of:

nl = document.getElementsByTagName("P");

for (var i = 0; i < nl.length; i++)
{
    p = nl[i];
}

for performance reasons.

I always used the "wrong" way, according the article, but, am I wrong or is the article wrong?

like image 371
Zanoni Avatar asked Aug 04 '09 20:08

Zanoni


2 Answers

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

--Donald Knuth


Personally i would use your way because it is more readable and easier to maintain. Then i would use a tool such as YSlow to profile the code and iron out the performance bottlenecks.

like image 114
Gary Willoughby Avatar answered Nov 02 '22 10:11

Gary Willoughby


If you look at it from a language like C#, you'd expect the second statement to be more efficient, however C# is not an interpreter language.

As the guide states: your browser is optimized to retrieved the right Nodes from live lists and does this a lot faster than retrieving them from the "cache" you define in your variable. Also you have to determine the length each iteration, with might cause a bit of performance loss as well.

Interpreter languages react differently from compiled languages, they're optimized in different ways.

like image 22
Zyphrax Avatar answered Nov 02 '22 09:11

Zyphrax