Sub topic 11
Box<str>, Rc<str> and Arc<str> for compact and shared data
This chapter assumes you know how String and Vec manage capacity, and the basics of Rc and Arc. It covers three types that store text you will not change: Box<str>, Rc<str> and Arc<str>.
Why String is often bigger than needed
A String holds three words: a pointer, a length and a capacity. The capacity lets you push more text, but many strings are written once and only read afterwards. Names, keys and file paths usually fit that pattern.
Box<str>, Rc<str> and Arc<str> hold a pointer and a length, so they have no capacity field. They are also exactly as large as their text, with no spare room. You can check the sizes yourself.
use std::mem::size_of;
use std::rc::Rc;
use std::sync::Arc;
fn main() {
println!("String: {}", size_of::<String>());
println!("Box<str>: {}", size_of::<Box<str>>());
println!("Rc<str>: {}", size_of::<Rc<str>>());
println!("Arc<str>: {}", size_of::<Arc<str>>());
}On a 64-bit target this prints 24 for String and 16 for the other three. Saving 8 bytes per value matters only when you store millions of them, for example as fields in a large Vec of records.
Box<str>: one owner, no spare capacity
Use Box<str> when a value has a single owner and will not grow. String::into_boxed_str converts to it. If the String has spare capacity, the conversion reallocates to shrink the buffer. If capacity already equals length, it reuses the buffer.
fn main() {
let mut s = String::with_capacity(100);
s.push_str("hello");
let boxed: Box<str> = s.into_boxed_str();
println!("{} ({} bytes)", boxed, boxed.len());
let back: String = boxed.into_string();
println!("{}", back);
}Rc<str> and Arc<str>: share instead of clone
Cloning a String allocates and copies the text. Cloning an Rc<str> copies a pointer and a length, then increments a reference count. It never allocates. Use Rc within one thread and Arc across threads. Arc uses atomic operations for the count, which cost slightly more.
use std::rc::Rc;
fn main() {
let name: Rc<str> = Rc::from("config.toml");
let a = Rc::clone(&name);
let b = Rc::clone(&name);
println!("{} {} {}", name, a, b);
println!("strong count = {}", Rc::strong_count(&name));
}This prints strong count = 3. All three handles point at one copy of the text.
Common errors
- Converting a String to Rc or Arc copies the text.
Rc::from(string)allocates a new block, because the reference counts live in the same allocation as the data. The original buffer is freed. Convert once when you create the value, then clone the handle many times. - Converting in a hot loop. Calling
Rc::from(s)for the same text on every iteration allocates every time. Create theRc<str>once and clone it. - Expecting to mutate. These types give you
&stronly. To change the text, build a newStringand convert again. - Using
Rcacross threads.Rc<str>is notSend, so the compiler rejects it. Switch toArc<str>. - Expecting a big win from small programs. Measure with the counting allocator from the earlier chapter. A few strings will not show a difference.
When it is worth it
Choose these types when you have many long-lived, read-only strings, or when the same text is duplicated across many records. A typical case is a field such as a country code or file path that repeats in thousands of structs. Sharing one Arc<str> removes the duplicate allocations and the copying.
Exercise
Why does cloning an Arc<str> not allocate, and what is the cost of the clone instead?
Show answer
The clone copies the pointer and length and increments an atomic reference count. The text itself stays in the one existing allocation. The cost is the atomic increment, which is cheap but not free, and the shared text lives until the last handle is dropped.