Sub topic 3
What a Clone Costs: `String` and `Vec` versus `Rc` and `Arc`
Assume you know Rust ownership, borrowing, structs, traits, and basic Cargo use.
What a clone costs
Clone is explicit, but its cost depends on the type. Cloning a String allocates new heap storage and copies its bytes. Cloning a Vec<T> allocates storage and clones every element. For Vec<String>, this can allocate once for the vector and again for each string.
Rc<T> and Arc<T> share their data. Cloning one copies a pointer and increases a reference count. Rc uses ordinary counting for single-threaded programs. Arc uses atomic counting and supports shared ownership across threads.
| Type | What `.clone()` usually does | Main cost |
|---|---|---|
| `String` or `Vec<T>` | Copies owned data | Allocation and element copying |
| `Rc<T>` | Shares data and increments a count | Small non-atomic count update |
| `Arc<T>` | Shares data and increments a count | Small atomic count update |
Using `Copy` and `Clone` as generic bounds
A Copy bound allows implicit duplication. A Clone bound requires an explicit call and works for more types.
fn pair_copy<T: Copy>(value: T) -> (T, T) {
(value, value)
}
fn pair_clone<T: Clone>(value: &T) -> (T, T) {
(value.clone(), value.clone())
}
fn main() {
println!("{:?}", pair_copy(7));
println!("{:?}", pair_clone(&String::from("hi")));
}Use the weakest bound that expresses the operation. Do not require Clone when borrowing is enough.
Writing `Clone` by hand
Derive Clone when each field should be cloned normally. Implement it manually when the type needs special behavior.
struct Counter {
hits: u32,
label: String,
}
impl Clone for Counter {
fn clone(&self) -> Self {
Self {
hits: self.hits,
label: self.label.clone(),
}
}
}
fn main() {
let original = Counter { hits: 3, label: String::from("home") };
let copy = original.clone();
println!("{} {}", copy.hits, copy.label);
}Deciding whether your type should be `Copy`
Choose Copy for small value types whose duplication is cheap and unsurprising. Every field must also be Copy. Choose Clone only when copying may allocate, perform work, or represent a deliberate duplicate. Choose neither for types that represent unique resources or identity.
`clone_from` and reused allocations
clone_from replaces an existing value. Types such as String can reuse the target's allocation.
fn main() {
let source = String::from("new text");
let mut target = String::with_capacity(64);
target.clone_from(&source);
println!("{target}");
}Pitfalls and Clippy lints
Avoid cloning just to satisfy the borrow checker. First try a reference, a shorter scope, or an iterator that yields references. Clippy can flag unnecessary calls with lints such as clone_on_copy and redundant_clone. Cloning an Rc or Arc is usually cheap, but it still changes ownership counts.
Exercise
Which operation is usually cheaper: cloning a Vec<String> or cloning an Arc<Vec<String>>? Why?
Show answer
Cloning the Arc is usually cheaper because it copies a pointer and updates an atomic count. Cloning the vector allocates storage and clones each string.