簡體   English   中英

Javascript性能:緩存與不緩存-奇怪的結果

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM