PHPStorm IDE 中低效的 jQuery 使用警告

我最近升级了我的 PHPStorm IDE 版本,它现在警告我 jQuery 使用效率低下。

例如:

var property_single_location = $("#property [data-role='content'] .container");

提示以下警告:

检查 jQuery 选择器的使用效率 分割子代选择器,其前面有 ID 选择器和 警告可能被缓存的重复选择器。

所以我的问题是:

为什么这是低效的,什么是有效的方法来做上述选择器?

我猜是:

var property_single_location = $("#property").find("[data-role='content']").find(".container");

这条路对吗?

23171 次浏览

I had the same question today and was able to find a solution thanks to Scott Kosman here.

Basically the answer is to select IDs individually and then use .find(...) for anything below. So taking your example:

$("#property [data-role='content'] .container");

Changing it to this makes PhpStorm happy and can evidently be more than twice as fast:

$("#property").find("[data-role='content'] .container");

I believe the difference between the two methods when using recent versions of jQuery and browsers is negligible. I constructed a test that shows that it is now actually 10% faster to do a combined selector rather than selection on id and then find for a very simple case:

http://jsperf.com/jquery-find-vs-insel

For selection of multiple children by class at any depth, the "find" does appear to be faster:

http://jsperf.com/jquery-find-vs-insel/7

There was some discussion about this on jQuery forums, but its 3 years old: https://forum.jquery.com/topic/which-jquery-selection-is-efficient As they point out here, if you are doing a lot of operations on same id selector, the greatest performance improvement is found by caching the top level element. On the other hand if you are doing just a few selections, there is going to be virtually no performance difference.

Therefor I believe that IntelliJ is overstating the importance of this code style.

The first question is to hit Alt+Enter, and select the first tip in the list, then hit Enter, you'll see what it thinks the most efficient way.