Best way to clone and append a single element?

I was previously using

let mut b = a.clone();
b.push(item);

But I found the following makes a significant performance difference in my use case

let mut b = Vec::with_capacity(a.len() + 1);
b.clone_from(&a);
b.push(item);

I was wondering if there is an already existing method to clone and append a single element?

Probably not, because doing that repeatedly is a very inefficient way to build a vector. You might be interested in im — data structures in Rust // Lib.rs

Or, if you're just looking for a one-liner, you could do

x.iter().chain([y]).cloned().collect()

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=068f7b43f7a1bc66b6648626a99eab4d

That iterator will have an accurate size_hint, so won't need to reallocate the way that clone+push does.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.