![](/img/trans.png)
[英]Is there any performance benefit to using $(this) vs caching selector to a variable?
[英]Javascript performance: Caching vs No Caching - weird results
我正在尝试优化一些遍历和隐藏/显示一些无序列表的基本jquery脚本。
这是jsperf中的测试用例: http ://jsperf.com/caching-vs-no-caching
我在两种浏览器中运行了该测试:Chrome和IE7 / IE8,令人惊讶的是,缓存的情况更慢-有点,但仍然如此。
未优化的版本是:
(function( $ ) {
$.fn.menuManipulation = function() {
this.parents().show();
};
})( jQuery );
$('.menu-vertical li.selected').menuManipulation();
$(".menu-vertical li.selected > ul.static").show();
$('li.static').has('ul').addClass("with-child");
和缓存的一个:
(function($) {
$.fn.menuManipulation = function() {
this.parents().show();
};
})(jQuery);
var menu = $('.menu-vertical');
menu.find('li.selected').menuManipulation();
menu.find('li.selected > ul.static').show();
menu.find('li.static').has('ul').addClass("with-child");
有人可以解释我在做什么错吗,为什么缓存的版本似乎慢一些?
简短的答案:选择器实际上非常快,但是find
却慢得要命。 您的缓存版本引入了多个find
调用-这很慢。
稍长的答案:如果您继续按原样重复使用,则只有从缓存jQuery集合中真正受益。 看一下这个测试案例,其中缓存的版本显然运行得更快: http : //jsperf.com/cachingjq
乔治,
在“已缓存”的情况下尝试此操作,看看性能差异是什么:
(function($) {
$.fn.menuManipulation = function() {
this.parents().show();
};
})(jQuery);
var menu = $('.menu-vertical');
$('li.selected', menu).menuManipulation();
$('li.selected > ul.static', menu).show();
$('li.static', menu).has('ul').addClass("with-child");
至于find()
是“地狱般缓慢”还是实际上像地狱般快速存在争议。 您的性能问题可能取决于您使用的jQuery版本或DOM的结构。
有关find()
性能的参数的另一面,请参见此处: jQuery选择器性能 , http : //seesparkbox.com/foundry/jquery_selector_performance_testing
基准测试: Find()与选择器
缓存您实际要处理的元素,在您的情况下为“ li”元素。
var menu = $('.menu-vertical li');
menu.filter('.selected').children('ul.static').show().end().menuManipulation();
menu.filter('.static').has('ul').addClass("with-child");
实际上,由于对li元素进行了额外的冗余搜索,因此“优化”的缓存版本实际上未得到优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.