Sub topic 8
What a clone costs: String and Vec versus Rc and Arc
This chapter assumes you know ownership and borrowing, the Clone trait, and how .clone() differs from an implicit Copy. Here you will learn what a clone actually does at runtime, so you can tell a cheap clone from an expensive one.
Clone is a method, so its cost varies
Copy is always a bitwise copy of a small value. Clone is ordinary code that the type's author wrote or derived, so it can do anything. The call looks the same for every type. The work behind it does not.
Two cases cover most of what you will meet:
- Deep copy. The clone allocates new memory and copies the data.
String,Vec<T>,HashMapandBox<T>work this way. The cost grows with the amount of data. - Shared ownership. The clone copies a pointer and bumps a counter.
Rc<T>andArc<T>work this way. The cost is constant, no matter how large the data is.
Deep clones: String and Vec
Cloning a String allocates a new heap buffer and copies every byte. Cloning a Vec<T> allocates a new buffer and clones each element, one by one. If the elements are themselves Vecs or Strings, each of those allocates too.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
let copy = names.clone();
// Same contents, different heap buffers.
println!("{}", names == copy);
println!("{}", names.as_ptr() == copy.as_ptr());
}The program prints true and then false. The vectors are equal, but they live at different addresses. Cloning names made three allocations here: one for the outer buffer and one for each string.
Shared clones: Rc and Arc
Rc<T> is a reference-counted pointer for single-threaded code. Arc<T> is the thread-safe version, which uses atomic counters. Cloning either one copies the pointer and increments the strong count. The underlying data is not touched.
use std::rc::Rc;
fn main() {
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
println!("{}", Rc::ptr_eq(&a, &b));
}This prints 2 and then true. Both handles point at one vector. The data is freed when the last handle is dropped.
The calls Rc::clone(&a) and a.clone() do the same thing. Many Rust programmers prefer the first form because it shows at a glance that the clone is cheap.
Arc is cheap, but not free
Arc::clone uses an atomic increment. That is far cheaper than copying a large buffer, but it costs more than a plain increment. Under heavy contention, many threads cloning the same Arc can slow each other down because they fight over one cache line. Use Rc when you stay on one thread.
Shared ownership also gives you only shared access. You cannot mutate through an Rc<T> or Arc<T> unless you add interior mutability, such as RefCell or Mutex.
Comparing the costs
| Type | What `.clone()` does | Cost |
|---|---|---|
| `i32`, `Point` (Copy) | Bitwise copy | Constant, tiny |
| `String` | Allocate and copy bytes | Proportional to length |
| `Vec<T>` | Allocate, then clone each element | Proportional to length and element cost |
| `Rc<T>` | Increment counter | Constant |
| `Arc<T>` | Atomic increment | Constant, slightly higher |
Common mistakes
- Cloning to silence the borrow checker. If you add
.clone()only to make an error disappear, try a reference first. A borrow costs nothing. - Cloning inside a loop. A clone per iteration multiplies the cost by the loop count. Move it out of the loop, or borrow.
- Assuming a clone is cheap because the type looks small. A
Vecof a million items is a small struct on the stack, but cloning it copies a million items. - Expecting a clone of
Rc<RefCell<T>>to give you an independent value. It gives you another handle to the same value. Changes made through one handle show up in the other.
Exercise
A function receives data: Rc<Vec<u8>> holding 10 MB. It calls data.clone() 1,000 times to give a handle to each of 1,000 tasks on one thread. Roughly how much data is copied, and what does Rc::strong_count report afterward, assuming no handle has been dropped?
Show answer
No bytes of the 10 MB buffer are copied, because each clone only copies the pointer and increments the counter. The count is 1,001: the original handle plus 1,000 clones. If data were a plain Vec<u8>, the same loop would copy about 10 GB.