在 jQuery 中,使用 filter() 更有效,还是只在each() 中这样做更有效?

发布于 2024-11-05 23:18:28 字数 1004 浏览 0 评论 0原文

我目前的代码通过 jQuery 提取数据,然后使用 each 方法显示它。

但是,我遇到了排序问题,因此我考虑在 sort 之前使用并添加 jQuery 的 filter 方法(这是有道理的)。

我现在正在考虑删除 sort,并且想知道是否应该按原样保留 filter 调用,或者将其移回 each.

过滤器的 jQuery API 文档 中的示例坚持使用样式结果,而不是文本内容的输出 (具体来说,不使用 each())。

文档当前指出“[t]他提供的选择器针对每个元素进行了测试[...]”,这让我相信做一个过滤器一个each 将导致非过滤元素循环两次,而如果仅在 each 循环中进行检查,则仅循环一次。

我认为这样更有效率是正确的吗?

编辑:虚拟示例。

所以这个:

// data is XML content
data = data.filter(function (a) {
    return ($(this).attr('display') == "true");
});
data.each(function () {
    // do stuff here to output to the page
});

与这个:

// data is XML content
data.each(function () {
    if ($(this).attr('display') == "true") {
        // do stuff here to output to the page
    }
});

I currently have code that is pulling in data via jQuery and then displaying it using the each method.

However, I was running into an issue with sorting, so I looked into using, and added, jQuery's filter method before the sort (which makes sense).

I'm now looking at removing the sort, and am wondering if I should leave the filter call as-is, or move it back into the each.

The examples in the jQuery API documentation for filter stick with styling results, not with the output of textual content (specifically, not using each()).

The documentation currently states that "[t]he supplied selector is tested against each element [...]," which makes me believe that doing a filter and an each would result in non-filtered elements being looped through twice, versus only once if the check was made solely in the each loop.

Am I correct in believing that is more efficient?

EDIT: Dummy example.

So this:

// data is XML content
data = data.filter(function (a) {
    return ($(this).attr('display') == "true");
});
data.each(function () {
    // do stuff here to output to the page
});

Versus this:

// data is XML content
data.each(function () {
    if ($(this).attr('display') == "true") {
        // do stuff here to output to the page
    }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谈场末日恋爱 2024-11-12 23:18:28

正如你所说:

文档目前指出
“提供的选择器是
针对每个元素进行测试[...]”

这让我相信做一个
过滤器和每个将导致
循环未过滤的元素
通过两次,而不是仅一次,如果
检查仅在每个
循环。

通过您的代码,我们可以清楚地看到您在两种情况下都使用了 each,这已经是一个循环filter 本身是另一个循环(带有一个if 用于过滤)。也就是说,我们正在比较两个循环一个循环之间的性能。不可避免地更少的循环=更好的性能

我创建了 这个 Fiddle 并使用 Firebug 分析工具。正如预期的那样,第二个选项只有一个循环更快。当然,对于如此少量的元素,差异仅为 0.062ms。但显然,随着元素的增多,差异会线性增加

由于很多人都超级担心说差异很小,应该根据可维护性来选择,所以我随意表达我的意见:我也同意这一点。事实上,我认为更易于维护的代码是没有过滤器的,但这只是一个品味问题。最后,您的问题是关于什么更有效,这就是答案,尽管差异很小。

Exactly as you said:

The documentation currently states
that "the supplied selector is
tested against each element [...]"
,
which makes me believe that doing a
filter and an each would result in
non-filtered elements being looped
through twice, versus only once if the
check was made solely in the each
loop.

Through your code we can clearly see that you are using each in both cases, what is already a loop. And the filter by itself is another loop (with an if it for filtering). That is, we are comparing performance between two loops with one loop. Inevitably less loops = better performance.

I created this Fiddle and profiled with Firebug Profiling Tool. As expected, the second option with only one loop is faster. Of course with this small amount of elements the difference was only 0.062ms. But obviously the difference would increase linearly with more elements.

Since many people are super worried to say the difference is small and you should choose according to the maintainability, I feel free to express my opinion: I also agree with that. In fact I think the more maintainable code is without the filter, but it's only a matter of taste. Finally, your question was about what was more efficient and this is what was answered, although the difference is small.

金兰素衣 2024-11-12 23:18:28

您是正确的,使用过滤器并且每个过滤器都较慢。仅使用每个循环速度更快。如果可能的话,请对其进行优化以使用更少的循环。

但这是一个微观优化。仅当它是“免费”且不以可读代码为代价时才应该对其进行优化。我个人会根据风格/可读性偏好而不是性能来选择使用其中一种。

除非您有大量 DOM 元素,否则您不会注意到其中的差异(如果您这样做,则会遇到更大的问题)。

如果您关心这种差异,那么您就会关心不使用 jQuery,因为 jQuery 很慢。

您应该关心的是可读性和可维护性。

$(selector).filter(function() {
    // get elements I care about
}).each(function() {
    // deal with them
});

vs

$(selector).each(function() {
    // get elements I care about
    if (condition) {
         // deal with them
    }
}

哪个使您的代码更具可读性和可维护性就是最佳选择。作为一个单独的注释过滤器,如果与 .map 一起使用,那么与 .each 一起使用会更强大。

我还要指出,从两个循环优化到一个循环就是从 O(n) 优化到 O(n)。那不是你应该关心的事情。过去我也觉得将所有内容都放在一个循环中“更好”,因为你只循环一次,但这确实限制了你使用map/reduce/filter。

编写有意义的、自记录的代码。只优化瓶颈。

You are correct that using filter and each is slower. It is faster to use just the each loop. Where possible do optimise it to use less loops.

But this is a micro optimisation. This should only be optimised when it's "free" and doesn't come at a cost of readable code. I would personally pick to use one or the other based on a style / readability preference rather then on performance.

Unless you've got a huge sets of DOM elements you won't notice the difference (and if you do then you've got bigger problems).

And if you care about this difference then you care about not using jQuery because jQuery is slow.

What you should care about is readability and maintainability.

$(selector).filter(function() {
    // get elements I care about
}).each(function() {
    // deal with them
});

vs

$(selector).each(function() {
    // get elements I care about
    if (condition) {
         // deal with them
    }
}

Whichever makes your code more readable and maintainable is the optimum choice. As a separate note filter is a lot more powerful if used with .map then if used with .each.

Let me also point out that optimising from two loops to one loop is optimising from O(n) to O(n). That's not something you should care about. In the past I also feel that it's "better" to put everything in one loop because you only loop once, but this really limits you in using map/reduce/filter.

Write meaningful, self-documenting code. Only optimise bottlenecks.

嘿嘿嘿 2024-11-12 23:18:28

我希望这里的性能非常相似,每个性能都稍快一些(在过滤集仍然很大的大型数据集中可能会很明显)。无论如何,过滤器可能只是在集合上循环(如果我错了,有人纠正我)。因此,第一个示例循环完整的集合,然后循环较小的集合。第二个只循环一次。

但是,如果可能的话,最快的方法是将过滤器包含在初始选择器中。假设您当前的数据变量是调用 $("div") 的结果。不要调用它然后过滤它,而是使用它来开始:

$("div[display='true']")

I would expect the performance here to be very similar, with the each being slightly faster (probably noticeable in large datasets where the filtered set is still large). Filter probably just loops over the set anyway (someone correct me if I'm wrong). So the first example loops the full set and then loops the smaller set. The 2nd just loops once.

However, if possible, the fastest way would be to include the filter in your initial selector. So lets say your current data variable is the result of calling $("div"). Instead of calling that and then filtering it, use this to begin with:

$("div[display='true']")
醉城メ夜风 2024-11-12 23:18:28

我通常不担心像这样的微观优化,因为在总体方案中,在性能方面您可能会比 jQuery .each() 与 jQuery 更需要担心。 .filter(),但要回答当前的问题,您应该能够使用一个 .filter() 获得最佳结果:

data.filter(function() {
  return ($(this).attr('display')==="true");
}).appendTo($('body'));

对于 .filter() 之间的原始性能比较code>.each() 和 .filter(),您可以查看此 codepen:

http://codepen.io/thdoan/pen/LWpwwa

但是,如果您只想输出带有 display="true" 的所有节点到页面,然后您可以简单地按照 James Montagne 的建议进行操作(假设节点是 ):

$('element[display=true]').appendTo($('body'));

I generally don't worry about micro-optimizations like this since in the grand scheme of things, you'll likely have a lot more to worry about in terms of performance than jQuery .each() vs. .filter(), but to answer the question at hand, you should be able to get the best results using one .filter():

data.filter(function() {
  return ($(this).attr('display')==="true");
}).appendTo($('body'));

For a primitive performance comparison between .each() and .filter(), you can check out this codepen:

http://codepen.io/thdoan/pen/LWpwwa

However, if all you're trying to do is output all nodes with display="true" to the page, then you can simply do as suggested by James Montagne (assuming the node is <element>):

$('element[display=true]').appendTo($('body'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文