getElementById()是否有效? [英] Is getElementById() efficient?

查看:76
本文介绍了getElementById()是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在我的方法中使用方法 getElementById(id1); 。我用它来查找HTML中的某些元素。我想知道如果每次都必须搜索整个DOM,我是否需要关注我使用它的程度。

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.

此方法如何工作?它是解析DOM并在找到它时返回元素,还是以某种方式将所有这些值编入索引,因此能够更快地返回?

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。我一般对这个方法很好奇,但是如果有任何不同的话我会使用Android WebView。

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

推荐答案

getElementById 非常快,你不必担心性能。

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

如果你一遍又一遍地使用相同的ID (并且一遍又一遍),你可能想要缓存它。性能增益可以忽略不计:

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();

检查对于一些基准测试,这个SO答案
Mike发布的结果是:

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


IE8 getElementById: 0.4844 ms

IE8 id数组查找:0.0062 ms

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

Chrome getElementById:0.0039 ms

Chrome id数组查找:0.0006 ms

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

Firefox 3.5与chrome相当。

Firefox 3.5 was comparable to chrome.

这篇关于getElementById()是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆