Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

11
  • 23
    The reason this is slow is because you're using + to create two new Strings on every iteration. If you use a single string (playground) it can work better than collect and join (playground). Commented Dec 21, 2020 at 7:15
  • 1
    v2 with black_box(xs).iter().copied() takes now twice as long for collect+join over fold (the black_box(xs) doesn't matter, xs is the same). <3 for microbenchmarking Commented Apr 19, 2021 at 12:54
  • 1
    Yes, they do Commented Apr 19, 2021 at 13:14
  • 1
    Another solution is let mut it = xs.into_iter(); let first = it.next().unwrap_or("").to_owned(); let r = it.fold(first, |a, b| a + "\n" + b); Then you end up with a String instead of &str Commented Mar 16, 2023 at 20:43
  • 1
    @mdonoughe You are wrong about that, no new strings are made while iterating. In Rust, String's + operator takes ownership of the strings, calls push_str(rhs) on it, and returns it. Commented Mar 12 at 16:00

lang-rust