Sub topic 12
clone_from and reusing existing allocations
This chapter assumes you know how Clone works, how String and Vec own heap memory, and what &mut references allow. It covers Clone::clone_from, a method that copies one value into another that already exists.
The problem with `x = y.clone()`
Suppose you already have a String called target, and you want it to hold the same text as source. The obvious code is:
fn main() {
let source = String::from("a longer piece of text");
let mut target = String::with_capacity(64);
target = source.clone();
println!("{target}");
}This works, but it does extra work. The call source.clone() allocates a new buffer and copies the text into it. The assignment then drops the old target, which frees its 64-byte buffer. One allocation and one deallocation happened, even though the old buffer was big enough to hold the text.
What `clone_from` does
Clone has a second method besides clone:
fn clone_from(&mut self, source: &Self)It overwrites self with a copy of source. A type may override it to reuse the memory that self already owns. The default version just does *self = source.clone(), so it is always correct but gains nothing.
String and Vec<T> override it. Here is the same job with clone_from:
fn main() {
let source = String::from("a longer piece of text");
let mut target = String::with_capacity(64);
target.clone_from(&source);
println!("{target}");
println!("{}", target.capacity() >= 64);
}The program prints the text, then true. The text fits in the existing buffer, so String copies the bytes in place. No new allocation happens and the old capacity is kept. If the text did not fit, the string would grow as usual.
Where it pays off: loops
A single call saves little. The benefit appears when you refresh the same variable many times, such as a buffer that holds the latest snapshot of some data.
fn main() {
let lines = vec![
String::from("first line of input"),
String::from("second"),
String::from("third line, a bit longer"),
];
let mut latest = String::new();
for line in &lines {
latest.clone_from(line);
println!("latest = {latest}");
}
}After the first iteration latest has a buffer large enough for most later lines, so later iterations allocate nothing unless a line is longer than anything seen so far. With latest = line.clone() every iteration would allocate and free.
Vec<T> goes further. When you call clone_from on a Vec<String>, it clones element by element into the existing slots, and each of those calls can reuse the inner String buffers too. Extra old elements are dropped, and missing ones are appended.
fn main() {
let source = vec![String::from("one"), String::from("two")];
let mut target = vec![String::from("old value"), String::from("x"), String::from("y")];
target.clone_from(&source);
println!("{:?}", target);
}This prints ["one", "two"].
Overriding it in your own types
If you write Clone by hand, you can override clone_from the same way. Delegate to each field's clone_from:
struct Record {
id: u32,
name: String,
tags: Vec<String>,
}
impl Clone for Record {
fn clone(&self) -> Self {
Record {
id: self.id,
name: self.name.clone(),
tags: self.tags.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.id = source.id;
self.name.clone_from(&source.name);
self.tags.clone_from(&source.tags);
}
}
fn main() {
let a = Record { id: 1, name: String::from("alpha"), tags: vec![String::from("x")] };
let mut b = Record { id: 2, name: String::new(), tags: Vec::new() };
b.clone_from(&a);
println!("{} {} {:?}", b.id, b.name, b.tags);
}Overriding is optional. #[derive(Clone)] generates only clone, so derived types use the default clone_from and get no reuse. Add the override only for types you refresh often, and only when profiling or allocation counts suggest it matters.
Rules and limits
clone_frommust leaveselfequal to whatsource.clone()would produce. It is an optimization, not a different operation.- It needs an existing value, so it cannot replace
clonewhen you are creating a new one. - It takes
&mut self, so it only works on a variable you can mutate. - Reuse is not guaranteed by the language. It is a property of the specific type's implementation.
Exercise
You keep a mut current: Vec<u8> that is refreshed from a &Vec<u8> called incoming on every loop pass. Which line should you write, and why is it better than current = incoming.clone();?
Show answer
Write current.clone_from(incoming);. It copies the bytes into the buffer current already owns, so it allocates only when the new data exceeds the existing capacity. The assignment version allocates a new buffer on every pass and frees the old one.