Sub topic 11
Box<str>, Rc<str> and Arc<str> for compact and shared data
This chapter assumes you know ownership and borrowing, the basic use of String and Vec, and how Rc and Arc count references. The earlier chapters showed how to avoid allocating at all. Here the data has to live on the heap, and the question is how to store it with less memory and fewer copies.
Why String is larger than it needs to be
A String is three machine words: a pointer to the heap buffer, a length, and a capacity. The capacity lets push_str append without reallocating on every call. Many strings are never modified after they are built, such as identifiers, file paths, configuration keys and tags. For those, the capacity field is wasted. The spare bytes at the end of the buffer are wasted too, because a growing String over-allocates.
Three alternatives store the text without a capacity:
Box<str>is an owned string slice. It has one owner and cannot grow.Rc<str>is a reference-counted string slice for single-threaded sharing.Arc<str>is the same with an atomic counter, so it can be shared across threads.
All three hold a pointer and a length, and nothing else. A pointer to an unsized type like str is a "fat pointer" with two words. 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>>());
println!("Rc<String> = {}", size_of::<Rc<String>>());
}On a 64-bit target this prints 24, 16, 16, 16 and 8. The saving is 8 bytes per value. That matters when you store millions of them, for example as fields in a large Vec of records.
Box<str>: an owned string that cannot grow
Convert a String with into_boxed_str. The conversion calls shrink_to_fit first, so the heap buffer is trimmed to exactly the string's length.
fn main() {
let mut s = String::with_capacity(100);
s.push_str("hello");
println!("len = {}, capacity = {}", s.len(), s.capacity());
let b: Box<str> = s.into_boxed_str();
println!("boxed: {} ({} bytes)", b, b.len());
let back: String = b.into_string();
println!("back to String: {}", back);
}Two details matter for allocation counts:
into_boxed_strmay reallocate. If capacity already equals length, it reuses the buffer. If not, the allocator is asked to shrink the block, and it may move it.into_stringnever allocates. ABox<str>has no spare capacity, so the buffer is reused as is, and the nextpush_strwill have to grow it.
Use Box<str> for text that is written once and read many times. A typical case is a field in a long-lived struct that was built from input and then frozen. Convert once, after the string is complete, not inside the building loop.
Rc<str> and Arc<str>: cheap clones of immutable text
Cloning a String allocates and copies the bytes. Cloning an Rc<str> increments a counter and copies two words. If the same text appears in many places, share one allocation.
use std::rc::Rc;
struct Token {
text: Rc<str>,
line: u32,
}
fn main() {
let name: Rc<str> = Rc::from("identifier");
let a = Token { text: Rc::clone(&name), line: 1 };
let b = Token { text: Rc::clone(&name), line: 2 };
println!("{} {} {}", a.text, b.line, Rc::strong_count(&name));
}This prints identifier 2 3. There are three owners and one heap block. Write Rc::clone(&name) rather than name.clone(). Both work, but the first makes it obvious that no text is copied, which helps when you review code for hidden allocations.
Use Arc<str> when the value crosses threads. Rc is not Send, so the compiler rejects it in thread::spawn. Arc uses atomic increments and decrements, which cost more than plain ones, especially when many threads clone and drop the same value. Choose Rc unless you need thread sharing.
Conversion is a copy
Rc<str> stores the reference counts and the text in the same heap block. A String's buffer has no room for counts, so Rc::from(string) allocates a new block, copies the bytes, and frees the old buffer. The same is true for Arc::from(string) and Rc::from(&str).
This changes how you build shared strings:
- Build the text in a
Stringfirst, withwith_capacityor a reused buffer. - Convert to
Rc<str>once, when the text is final. - Do not convert in a loop and then expect the conversion to be free. It costs one allocation, one copy and one free each time.
The saving comes later, from every clone you no longer make.
A worked use: interning
Interning stores one copy of each distinct string and hands out shared handles. It fits programs that see the same names repeatedly, such as parsers, log processors and symbol tables.
use std::collections::HashSet;
use std::sync::Arc;
#[derive(Default)]
struct Interner {
set: HashSet<Arc<str>>,
}
impl Interner {
fn intern(&mut self, s: &str) -> Arc<str> {
if let Some(existing) = self.set.get(s) {
return Arc::clone(existing);
}
let new: Arc<str> = Arc::from(s);
self.set.insert(Arc::clone(&new));
new
}
}
fn main() {
let mut interner = Interner::default();
let a = interner.intern("host");
let b = interner.intern("host");
println!("{} {}", Arc::ptr_eq(&a, &b), Arc::strong_count(&a));
}This prints true 3: the set, a and b all point to one block. The lookup self.set.get(s) takes a &str and allocates nothing, because Arc<str> implements Borrow<str>. A new Arc is created only on the first sighting of each distinct string.
The table is never pruned in this version, so the strings live as long as the interner does. That is the usual trade-off of interning: fewer allocations and faster comparisons, in exchange for holding every distinct value.
The same idea for slices
The pattern is not specific to strings. For any T:
Vec<T>becomesBox<[T]>withinto_boxed_slice.Vec<T>becomesRc<[T]>orArc<[T]>withRc::from(vec), which copies the elements into a new block.Box<[T]>becomesVec<T>again withinto_vec, without allocating.
A Vec<Vec<u32>> of rows that never change length is a good candidate for Vec<Box<[u32]>>. Each row saves 8 bytes of header, and the unused capacity in each row is released.
Gotchas and trade-offs
- No growth. These types have no
push_str. To change the text, convert back to aString(forBox<str>) or build a new value. ForRc<str>andArc<str>,get_mutcan give you a&mut stronly when the count is 1, and you still cannot change its length. - Fat pointer versus double indirection.
Rc<String>is 8 bytes but needs two pointer hops to reach the text: one to theRcblock, then one to the string's buffer.Rc<str>is 16 bytes with one hop. For hot read paths, the single hop is usually better. For structs where size dominates,Rc<String>can be smaller. - Shrinking can cost more than it saves.
into_boxed_stron a string that was over-allocated may copy the bytes into a smaller block. Do it for data that lives long, not for temporary strings. - Sharing needs repetition. If every string is distinct,
Rc<str>adds counter overhead (two words per block) and saves nothing on clones. Measure with the counting allocator from the earlier chapter before changing types. - Reference cycles.
RcandArcleak if values hold each other. Strings do not hold references, so this only matters if you wrap structures that do.
| Need | Type | Clone cost | Size on 64-bit | Can grow |
|---|---|---|---|---|
| Build or edit text | `String` | allocate and copy | 24 bytes | yes |
| One owner, frozen text | `Box<str>` | allocate and copy | 16 bytes | no |
| Shared, single thread | `Rc<str>` | counter increment | 16 bytes | no |
| Shared across threads | `Arc<str>` | atomic increment | 16 bytes | no |
Choosing
Use this order of questions:
- Do you need to modify the text after creation? Keep
String. - Is the text owned by one place, and long-lived? Use
Box<str>. - Does the same text get cloned or stored in many places? Use
Rc<str>, orArc<str>if threads are involved. - Do you see many repeated distinct values from input? Consider an interner.
Function parameters should still take &str, as in the borrowing chapter. These types are for what you store, not what you pass.
Exercise
A parser reads a 50 MB log file and creates one String per line for the host name, then stores each in a struct. About 40 distinct host names appear across 2 million lines. Which type would you store in the struct, and what would you do when building it, to cut allocations the most?
Show answer
Use Arc<str> (or Rc<str> if the parser is single-threaded) together with an interner like the one above. For each line, call intern(&line_host) with a borrowed &str. The lookup allocates nothing, and a new block is created only for the first occurrence of each of the 40 hosts. That reduces roughly 2 million host allocations to 40, and every struct holds a 16-byte handle instead of a 24-byte String. Box<str> would shrink each value but would still need one allocation per line.
Exercise
Why does Rc::from(my_string) allocate, even though my_string already lives on the heap?
Show answer
Rc<str> keeps its strong and weak counts in the same heap block as the text. The buffer of a String has no room for those counts, so the conversion must allocate a new block, copy the bytes, and free the old buffer.