Javascript性能:缓存与无缓存 - 奇怪的结果

Geo*_*nos 0 performance jquery dom

我正在尝试优化一些遍历和隐藏/显示一些无序列表的基本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");
Run Code Online (Sandbox Code Playgroud)

和缓存的:

(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");
Run Code Online (Sandbox Code Playgroud)

有人可以解释我做错了什么,为什么缓存版本似乎更慢?

Jam*_*iec 5

简短回答:选择器实际上非常快,但find速度很慢.您的缓存版本引入了多个find调用 - 这很慢.

稍微长一点的答案:如果你继续按原样重新使用它,你只能从缓存jQuery集合中获益.看看这个缓存版本运行得更快的测试用例:http://jsperf.com/cachingjq