Is getElementById() efficient? [duplicate]

北战南征 提交于 2019-12-21 08:05:15

问题


I often use the method getElementById("id1"); in my methods. I use it to find certain elements in my HTML. I wonder if I need to be concerned about how much I use it if it has to search the entire DOM every time.

How does this method work? Does it parse the DOM and return the element when it is found, or does it have all those values indexed somehow and so is able to return more quickly?

P.S. I am curious about the method in general, but I am using an Android WebView if that makes any difference.


回答1:


getElementById is very fast and you shouldn't have to worry about performance.

If you are using the same ID over and over (and over and over) again, you might want to cache it. The performance gain is neglectable:

var myId = getElementById("myId");
myId.operation1();
myId.operation2();
myId.andSome5000MoreCalls();

Check this SO answer for some benchmarks. The results Mike posted were:

IE8 getElementById: 0.4844 ms
IE8 id array lookup: 0.0062 ms

Chrome getElementById: 0.0039 ms
Chrome id array lookup: 0.0006 ms

Firefox 3.5 was comparable to chrome.




回答2:


In fact getElementById is the fastest way to access an element in the DOM. Indexing depends on the specific browser, but here is a benchmark for it:

http://jsperf.com/getelementbyid-vs-everyone-else




回答3:


Elements with IDs are indeed indexed, selecting an element by its ID through the DOM function is the most efficient way of selection.



来源:https://stackoverflow.com/questions/12514970/is-getelementbyid-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!