Use Case for Box<str> and String

As far as I know there is exactly one reason to use Box<str> over String. On my computer:

use std::mem::size_of;

fn main() {
    println!("{}", size_of::<Box<str>>()); // 16
    println!("{}", size_of::<String>()); // 24
}

String stores pointer+length+capacity while Box<str> stores pointer+size. The capacity allows String to append efficiently. The compiler uses Box<str> as an optimization when it has a massive number of immutable strings so size matters, for example the string interner:

https://github.com/rust-lang/rust/blob/7846610470392abc3ab1470853bbe7b408fe4254/src/libsyntax/symbol.rs#L82-L85

21 Likes