Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript getelementsbytagname efficiency

This is my HTML Code

<html> 
  <head>
     <title> Test Page </title>
     <script type='text/javascript'>
        function test() {
           var ta = document.getElementsByTagName('body')[0].getElementsByTagName('li');
        }
     </script>
  </head>
  <body onload='test()'>
     <ul>
        <li> Test 1 </li>
        <li> Test 1 </li>
        <li> Test 1 </li>
        <li> Test 1 </li>
     </ul>
  </body>
</html>

Which of the following is better and why?

document.getElementsByTagName('body')[0].getElementsByTagName('li')

document.getElementsByTagName('li')

Also I couldn't find any documentation or reference for getElementsByTagName implementation across browsers [atleast a overview on some major browsers] although I found really interesting things about document.getElementById that it is kind of hash look up atleast in firefox and chrome. Wish to have some help on the implementation too.

like image 794
Tamil Avatar asked Feb 11 '12 16:02

Tamil


2 Answers

First of all, you should never get the body tag with this:

document.getElementsByTagName('body')[0]

It's always more efficient to just use the built-in property for the body:

document.body

Second of all, all performance questions should be answered by testing with a tool like jsPerf. In this case, you can build a test that compares between these two if you want, but I think the point is moot given the previous simplification:

document.getElementsByTagName("li")

and

document.body.getElementsByTagName("li")

In a jsPerf I built to test this, document.getElementsByTagName('li') is the fastest, followed by document.body.getElementsByTagName('li') and document.getElementsByTagName('body')[0].getElementsByTagName('li') is the slowest.

Here's a screenshot of the test from several browsers:

enter image description here

like image 188
jfriend00 Avatar answered Oct 24 '22 12:10

jfriend00


First off, you should avoid functions inside functions to improve performance and on top of that DOM is slow.

You can refactor your code like this:

function getLis(){
  return document.getElementsByTagName('li');
}

function test() {
  var ta = getLis();
}

This way, javascript only stores these two functions in memory once and you call call them as many times as you want.

For your question, later should be faster because it has one call less:

document.getElementsByTagName('li')

As for speed, my guess was correct, I have created test case at jsperf:

Speed Test

Results:

document.getElementsByTagName('li')

2,141,067
±2.07%
fastest

document.getElementsByTagName('body')[0].getElementsByTagName('li')

704,856
±4.40%
67% slower

And Screenshot:

enter image description here

like image 43
Sarfraz Avatar answered Oct 24 '22 10:10

Sarfraz