性能问题:存储对DOM元素的引用与使用选择器 [英] performance issue : storing a reference to DOM element vs using selectors

查看:94
本文介绍了性能问题:存储对DOM元素的引用与使用选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的应用程序中,用户可以在某些div标签内创建一些内容,并且每个内容,或者我称之为元素"的元素都有其自己的对象.目前,我使用一个函数来计算使用jquery选择器将元素放置在其中的原始div标签,但是我想知道在性能方面,一旦元素具有被创建,而不是稍后进行计算? 所以现在我使用这样的东西:

So in my app, the user can create some content inside certain div tags, and each content, or as I call them "elements" has its own object. Currently I use a function to calculate the original div tag that the element has been placed inside using jquery selectors, but I was wondering in terms of performance, wouldn't it be better to just store a reference to the div tag once the element has been created, instead of calculating it later ? so right now I use something like this :

$('.div[value='+divID+']')

但是,相反,我可以在创建元素时将引用存储在元素内.这样对性能会更好吗?

but instead I can just store the reference inside the element, when im creating the element. Would that be better for performance ?

推荐答案

如果您有很多这样的绑定,则最好存储对它们的引用.如评论中所述,变量查找比在DOM中查找要快得多-尤其是使用当前方法. jQuery选择器比纯DOM选择器慢,并且该特定选择器将非常慢.

If you have lots of these bindings it would be a good idea to store references to them. As mentioned in the comments, variable lookups are much much faster than looking things up in the DOM - especially with your current approach. jQuery selectors are slower than the pure DOM alternatives, and that particular selector will be very slow.

这是一项基于epascarello的测试,显示了jQuery,DOM2方法和引用之间的区别: http://jsperf.com/test-reference-vs-lookup/2 .变量分配超预期.而且,DOM方法在很大程度上击败了jQuery.请注意,这里以Yahoo的主页为例.

Here is a test based on the one by epascarello showing the difference between jQuery, DOM2 methods, and references: http://jsperf.com/test-reference-vs-lookup/2. The variable assignment is super fast as expected. Also, the DOM methods beat jQuery by an equally large margin. Note, that this is with Yahoo's home page as an example.

另一个要考虑的是DOM的大小和复杂性.随着这种增加,引用缓存方法仍然变得更加有利.

Another consideration is the size and complexity of the DOM. As this increases, the reference caching method becomes more favourable still.

这篇关于性能问题:存储对DOM元素的引用与使用选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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