5

次のjQueryコードを検討してください。

if ($(this).is(':hidden')) {
    $(this).show();
}

私の質問:

  • show()コマンドを発行する前に、要素の可視性を確認する価値はありますか?
    • つまり、DOMの書き込みはDOMの読み取りよりもコストがかかりますか?また、このパターンには小さなパフォーマンスの最適化が含まれていますか?
  • または、ユーティリティがないことの可視性チェックであり、show()コマンドを単純に無条件に発行する方がクリーンなコードでしょうか?
4

3 に答える 3

6

表示したい場合は、非表示になっているかどうかを確認する必要はありません。表示するだけです。そもそも条件付きチェックを行わないことには小さなパフォーマンス上の利点があると思いますが、それはかなり無視できるかもしれないと私は確信しています。

チェックを行わないと実行が25%速くなることを示すパフォーマンステストを作成しました。これは、 http://jsperf.com/is-hidden-checkでオンラインで表示(およびいくつかのブラウザーでテスト)できます。

于 2012-04-22T16:13:28.800 に答える
2

せいぜい速度の増加を最小限に抑えることは別として、これが常に希望どおりに動作するとは限らない可能性があります。

ソース

:hiddenの決定方法は、jQuery1.3.2で変更されました。要素またはその親のいずれかがドキュメント内のスペースを消費しない場合、要素は非表示になっていると見なされます。CSSの可視性は考慮されていません(したがって $(elem).css('visibility','hidden').is(':hidden') == false)。

Checking for visibility is not incredibly complex, but IMHO even this excerpt shows it is not exactly trivial. While you could deal with the issue of making sure your visibility check works properly while using :hidden every time you want to make sure this code is working correctly, you could just forget the 5 milliseconds that you might have a chance at saving and instead save yourself the time spent to understand the code and check the documentation every time there might be a problem with this area.

Just use plain old show(); if there was a reason to do a check beforehand, I'm confident that the good ol' folks who make jQuery would have either provided a recommendation to do so in the docs somewhere or just hardcoded the check into the show method/ :D

于 2012-04-22T16:27:01.777 に答える
0

可視性チェックは、実際に非表示になっていない場合は.show()を発行しないため、労力を節約できる可能性があります。

だから私はそれで行くと思います

于 2012-04-22T16:15:05.843 に答える