When does Cow<'a, str> actually save an allocation, and when is it noise?
Cow<'a, str> holds a borrowed &str or an owned String and derefs to str. It saves an allocation when most calls return the input as is, like a normalize that copies only text with tabs. If almost every call builds a string, it is noise.
- Taking
Cowfor a reference counter or a thread-sharing type, when it is an enum of two variants - Expecting
to_mut()to clone on every call, though it clones once and only a borrowed value - Returning
Cowfrom a function whose result is almost alwaysOwned, gaining nothing but a harder signature
- Why does
String::from_utf8_lossyreturn aCow<str>and not aString? - When would you return
Cow<'static, str>from a function?
normalize allocates only when the input contains a tab; otherwise the result borrows the input:
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains('\t') {
Cow::Owned(input.replace('\t', " "))
} else {
Cow::Borrowed(input)
}
}
fn print_len(s: &str) {
println!("{} {}", s, s.len());
}
fn main() {
for line in ["plain", "a\tb"] {
let n = normalize(line);
let kind = if matches!(n, Cow::Borrowed(_)) { "borrowed" } else { "owned" };
println!("{kind}");
print_len(&n);
}
}The program prints borrowed, plain 5, owned, a b 6. The caller does not match on the variants: &n coerces to &str through Deref, just like a &String. With a million such strings and a tab in one of a hundred, Cow removes 99% of the allocations compared with a -> String signature.
There is no gain in two cases. If the string changes almost every time, the Cow is almost always Owned — the same allocation plus a branch and a lifetime in the signature. If the caller needs a String anyway (to store it in a struct or send it to another thread), it calls into_owned(), and the borrowed variant is copied there. A Cow<str> takes 24 bytes, like a String, so its only saving is that it leaves the heap alone.