.cloned()应该在.filter()之前还是之后

编程入门 行业动态 更新时间:2024-10-24 06:28:22
本文介绍了.cloned()应该在.filter()之前还是之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

比方说,我有矢量,我只想保留偶数元素.我将需要使用cloned()和filter().例如:

Let's say that I have vector and I want just keep the even elements. I would need to used cloned() and filter(). For example:

fn main() { let my_vec: Vec<i32> = vec![1,2,3,4]; let my_vec_1: Vec<i32> = my_vec.iter().cloned().filter(|&x| x % 2 == 0).collect(); println!("{:?}", my_vec_1); let my_vec_2: Vec<i32> = my_vec.iter().filter(|&x| x % 2 == 0).cloned().collect(); println!("{:?}", my_vec_2); }

两种方法都能奏效.在filter()之后使用cloned()似乎更有效率.因为那样,我不必将迭代器的所有元素都从&T转换为T,而只需将已过滤的元素转换即可.在我的示例中,这只是元素的一半.

Both approaches work. Using cloned() after filter() seems a little bit more efficient. Because then I don't have to convert all elements of the iterator from &T to T, but only the ones that have been filtered. In my example that's half the elements.

但是,我似乎看到在filter()之前应用了cloned().这是一个示例: method.inspect

However, I seem to see cloned() applied before filter(). Here is one example: method.inspect

我认为对于没有实现Copy特征的类型,也许必须先使用.cloned(),但是事实并非如此:嵌套的vec示例.另外,由于过滤器使用FnMut(&Self::Item),所以我认为这应该不是问题.

I thought that maybe .cloned() has to be used before for types that don't implement Copy trait, but it does not seem to be the case: nested vec example. Also, because filter uses FnMut(&Self::Item), I don' think that should be a problem.

在filter()之前使用cloned()有优势吗?这更多是风格问题吗?如果是这样,有没有首选的风格?

Are there advantages to using cloned() before filter()? Is this more of a stylistic issue? If so, is there preferred style?

推荐答案

这与样式无关.

以inspect的示例为例来说明inspect.它以愚蠢的方式使用.cloned,但之所以选择cloned是因为其易于理解的语义,从而创建了易于理解的复杂迭代器序列".

The example of inspect is made to show-case inspect, that is all. It uses .cloned in an arguably silly way, but cloned was probably chosen because of its easy to understand semantic so as to create an easy to understand "complex iterator sequence".

那么,.cloned()在.filter(...)之前还是之后?正如您提到的那样,除非克隆对于过滤是必需的(这令人惊讶),否则经验法则是在克隆之后再进行克隆,以最大程度地减少克隆元素的数量.

So, .cloned() before or after .filter(...) ? As you mention, unless cloning is necessary for filtering (which would be surprising) the rule of thumb will be to clone after so as to minimize the number of cloned elements.

这里没有风格,只是一个务实的绩效评估.

No style here, just a pragmatic performance assessment.

更多推荐

.cloned()应该在.filter()之前还是之后

本文发布于:2023-10-27 11:36:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533240.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:cloned   filter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!