about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDylan DPC <99973273+Dylan-DPC@users.noreply.github.com>2022-03-23 03:05:28 +0100
committerGitHub <noreply@github.com>2022-03-23 03:05:28 +0100
commit0e86cabdceb4205572505b9d238f7a4e859c362b (patch)
tree08e9d23f4d2759919227727afa200d4c9f93c2e5
parent67d6cc6ef3883b6598ee6347f119cdfd7c4029b8 (diff)
parent1fb43f66624554d3fd63afc8e141386cbd6d414b (diff)
downloadrust-0e86cabdceb4205572505b9d238f7a4e859c362b.tar.gz
rust-0e86cabdceb4205572505b9d238f7a4e859c362b.zip
Rollup merge of #92955 - llogiq:cloned-side-effect-doc, r=yaahc
add perf side effect docs to `Iterator::cloned()`

Now that #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`
-rw-r--r--library/core/src/iter/traits/iterator.rs16
1 files changed, 16 insertions, 0 deletions
diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs
index b62e8dfe1d6..53fbe4cbc42 100644
--- a/library/core/src/iter/traits/iterator.rs
+++ b/library/core/src/iter/traits/iterator.rs
@@ -3189,6 +3189,10 @@ pub trait Iterator {
     /// This is useful when you have an iterator over `&T`, but you need an
     /// iterator over `T`.
     ///
+    /// There is no guarantee whatsoever about the `clone` method actually
+    /// being called *or* optimized away. So code should not depend on
+    /// either.
+    ///
     /// [`clone`]: Clone::clone
     ///
     /// # Examples
@@ -3206,6 +3210,18 @@ pub trait Iterator {
     /// assert_eq!(v_cloned, vec![1, 2, 3]);
     /// assert_eq!(v_map, vec![1, 2, 3]);
     /// ```
+    ///
+    /// To get the best performance, try to clone late:
+    ///
+    /// ```
+    /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
+    /// // don't do this:
+    /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
+    /// assert_eq!(&[vec![23]], &slower[..]);
+    /// // instead call `cloned` late
+    /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
+    /// assert_eq!(&[vec![23]], &faster[..]);
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
     where