How to Optimize String Usage in Rust (String vs &str vs Cow)

Choose &str for borrowing, String for ownership, and Cow for conditional mutation to optimize Rust string performance.

Use &str for read-only references, String for owned mutable text, and Cow<'a, str> when you might need to mutate borrowed data without always allocating.

use std::borrow::Cow;

fn process(s: &str) -> Cow<'_, str> {
    if s.contains(" ") {
        Cow::Owned(s.to_uppercase())
    } else {
        Cow::Borrowed(s)
    }
}