Skip to content

Commit af11c71

Browse files
authored
Rollup merge of rust-lang#92955 - llogiq:cloned-side-effect-doc, r=yaahc
add perf side effect docs to `Iterator::cloned()` Now that rust-lang#90209 has been closed, as the current state of affairs is neither here nor there, this at least adds a paragraph + example on what to expect performance-wise and how to deal with it to the .cloned() docs. cc `@the8472`
2 parents 574eb46 + 7d62544 commit af11c71

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

core/src/iter/traits/iterator.rs

+16
Original file line numberDiff line numberDiff line change
@@ -3189,6 +3189,10 @@ pub trait Iterator {
31893189
/// This is useful when you have an iterator over `&T`, but you need an
31903190
/// iterator over `T`.
31913191
///
3192+
/// There is no guarantee whatsoever about the `clone` method actually
3193+
/// being called *or* optimized away. So code should not depend on
3194+
/// either.
3195+
///
31923196
/// [`clone`]: Clone::clone
31933197
///
31943198
/// # Examples
@@ -3206,6 +3210,18 @@ pub trait Iterator {
32063210
/// assert_eq!(v_cloned, vec![1, 2, 3]);
32073211
/// assert_eq!(v_map, vec![1, 2, 3]);
32083212
/// ```
3213+
///
3214+
/// To get the best performance, try to clone late:
3215+
///
3216+
/// ```
3217+
/// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3218+
/// // don't do this:
3219+
/// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3220+
/// assert_eq!(&[vec![23]], &slower[..]);
3221+
/// // instead call `cloned` late
3222+
/// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3223+
/// assert_eq!(&[vec![23]], &faster[..]);
3224+
/// ```
32093225
#[stable(feature = "rust1", since = "1.0.0")]
32103226
fn cloned<'a, T: 'a>(self) -> Cloned<Self>
32113227
where

0 commit comments

Comments
 (0)