Sub topic 8
What a clone costs: String and Vec versus Rc and Arc
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Clone and Copy differ. Here the question is practical: when you write .clone(), what work does the program do, and when is that work cheap?
Clone is a promise about semantics, not about cost
The Clone trait says only that .clone() returns an independent value that is equal in meaning to the original. It says nothing about speed. Two calls that look the same can differ by many orders of magnitude.
- Cloning an
i32copies four bytes. - Cloning a
Stringallocates new heap memory and copies every byte. - Cloning a
Vec<String>allocates for the vector and then allocates again for every string inside it. - Cloning an
Rc<T>increments a counter and copies one pointer. TheTis not touched.
Because .clone() looks identical in all four cases, you have to know the type to know the cost.
Deep copies: String and Vec
String and Vec<T> each own a heap buffer. The value on the stack is a small header of three words: a pointer, a length, and a capacity. A clone must produce a second, separate buffer, so that changing one value never affects the other.
fn main() {
let a = String::from("hello");
let b = a.clone();
println!("{:p} {:p}", a.as_ptr(), b.as_ptr());
println!("{}", a.as_ptr() == b.as_ptr());
}The two pointers differ, and the program prints false for the comparison. Each string has its own buffer.
The cost of a String clone is one allocation plus a copy of len bytes. That is O(n) in the length of the string. The capacity of the clone is usually its length, not the original capacity, so the clone may be smaller in memory than the source.
A Vec<T> is more subtle. Its clone cost depends on T:
- If
TisCopy, such asu8orf64, the standard library can copy the whole buffer in one step. This is one allocation and a fast memory copy. - If
Tis notCopy, each element has to be cloned on its own. ForVec<String>that means one allocation for the outer buffer and one more for each string.
Nested structures compound this. A Vec<Vec<String>> clone allocates once for the outer vector, once per inner vector, and once per string.
fn main() {
let rows: Vec<Vec<String>> = vec![
vec![String::from("a"), String::from("b")],
vec![String::from("c")],
];
// 1 outer + 2 inner + 3 strings = 6 allocations
let copy = rows.clone();
println!("{:?}", copy);
}The Clone for Vec<Vec<String>> is deep. Every owned piece of data is duplicated, down to the last string.
Shared ownership: Rc and Arc
Rc<T> and Arc<T> are reference-counted pointers. The value lives in one heap allocation along with a counter. Cloning the pointer does not clone the value. It increments the counter and returns another pointer to the same allocation.
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 a and b point to the same vector. When the last Rc is dropped, the count reaches zero and the vector is freed.
The cost of an Rc clone is constant. It does not depend on the size of the value inside. A clone of an Rc<Vec<u8>> holding a gigabyte costs the same as one holding three bytes.
The diagram below shows the difference in memory.
Rc versus Arc
Rc and Arc behave the same way at the API level. They differ in how the counter is updated.
| Type | Counter updates | Can cross threads | Clone cost |
|---|---|---|---|
| `Rc<T>` | Plain integer increment | No, it is not `Send` | A few instructions |
| `Arc<T>` | Atomic increment | Yes, when `T: Send + Sync` | A few instructions, plus atomic overhead |
An atomic operation is slower than a plain increment, and it can become much slower when many threads clone the same Arc at once, because the cores contend for the same cache line. Even so, an Arc clone is almost always far cheaper than a deep copy of anything of real size. Use Rc in single-threaded code and Arc when the value has to move between threads. The compiler enforces this, since an Rc cannot be sent to another thread.
Shared means read-only by default
Two pointers to one value cannot both mutate it freely. Rc<T> and Arc<T> give you only shared access. If you need to change the contents, you have three options:
- Wrap the value in interior mutability, for example
Rc<RefCell<T>>orArc<Mutex<T>>. - Use
Rc::make_mutorArc::make_mut, which clones the inner value only when it is shared. If you hold the only pointer, it mutates in place. - Go back to owned data and a deep clone.
The second option is called clone-on-write, and it pays the deep-copy cost only when a second owner exists.
use std::rc::Rc;
fn main() {
let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
// `a` is shared with `b`, so make_mut clones the vector first.
Rc::make_mut(&mut a).push(4);
println!("{:?} {:?}", a, b);
println!("{}", Rc::ptr_eq(&a, &b));
}This prints [1, 2, 3, 4] [1, 2, 3] and then false. After the write, the two pointers no longer share an allocation.
Cloning a struct clones its fields
A derived Clone on a struct calls .clone() on each field. The total cost is the sum of those calls. A struct is cheap to clone only if all its fields are.
use std::rc::Rc;
#[derive(Clone)]
struct Document {
id: u32,
title: String,
body: Rc<String>,
}
fn main() {
let d = Document {
id: 1,
title: String::from("Notes"),
body: Rc::new(String::from("a very long body of text")),
};
let e = d.clone();
println!("{}", d.title == e.title);
println!("{}", Rc::ptr_eq(&d.body, &e.body));
}Cloning Document allocates a new buffer for title and copies it. It does not copy body, because that field is an Rc. The program prints true and true: the titles are equal in content, and the bodies are the same allocation.
This is a common design choice. Large, read-only data goes behind an Rc or Arc so that cloning the surrounding struct stays cheap.
Reducing cost without changing the type
Before reaching for Rc, check whether you need to clone at all. In many cases a reference works.
fn word_count(text: &str) -> usize {
text.split_whitespace().count()
}
fn main() {
let s = String::from("one two three");
println!("{}", word_count(&s));
println!("{s}");
}The function borrows the string, so no copy occurs and s is still usable afterward. Accepting &str rather than String also lets callers pass string literals and slices.
A rough order of preference when two places need the same data:
- Borrow it with a reference, if the lifetimes allow.
- Share it with
RcorArc, if both places need ownership. - Clone it, if each place needs its own independent, mutable copy.
Measuring instead of guessing
A clone that looks expensive may not matter, and one that looks harmless may sit in a hot loop. Measure before rewriting. The standard library's Instant gives a quick comparison.
use std::rc::Rc;
use std::time::Instant;
fn main() {
let big: Vec<u8> = vec![0; 10_000_000];
let shared = Rc::new(big.clone());
let start = Instant::now();
let mut keep = Vec::new();
for _ in 0..20 {
keep.push(big.clone());
}
println!("vec clones: {:?}", start.elapsed());
let start = Instant::now();
let mut keep_rc = Vec::new();
for _ in 0..20 {
keep_rc.push(Rc::clone(&shared));
}
println!("rc clones: {:?}", start.elapsed());
println!("{} {}", keep.len(), keep_rc.len());
}Exact numbers depend on your machine and build mode. Run with cargo run --release for meaningful figures. The Vec loop copies about 200 MB in total, while the Rc loop does twenty increments. For serious benchmarking, use a harness such as Criterion, which guards against the optimizer removing work.
Edge cases
- Reference cycles. If two
Rcvalues point at each other, the counts never reach zero and the memory leaks. UseWeak<T>for back-references. - Capacity. A cloned
Vecusually has capacity equal to its length. If you plan to push onto the clone, reserve space first to avoid a reallocation. - Cloning a reference. Calling
.clone()on a&Stringgives aString. Calling it on a&TwhereTis notClonecopies the reference itself and gives a&T, which is often not what you meant. - Cheap is not free in hot paths. Even an atomic increment on a heavily shared
Arccan limit throughput across many cores.
Exercise
A struct has fields id: u64, name: String, and tags: Arc<Vec<String>>, and derives Clone. How many heap allocations does cloning it perform, and which field is the cheap one?
Show answer
One allocation. Cloning name allocates and copies a new buffer. Cloning tags only increments the atomic counter and copies a pointer, so it performs no allocation and does not copy the vector. The id field is copied by value with no allocation. The tags field is the cheap one relative to its size.
Exercise
You hold let mut a = Rc::new(vec![1, 2, 3]); and let b = Rc::clone(&a);. What happens when you call Rc::make_mut(&mut a).push(4), and what would be different if b had never been created?
Show answer
Because b shares the allocation, make_mut clones the vector into a new allocation for a, then pushes 4 onto that copy. b still sees [1, 2, 3]. If b had never been created, a would be the only owner, so make_mut would mutate the vector in place with no clone.