Maybe allocating a string

I have a function:

fn f(...) -> ???;

Where ??? is a type like String. On one platform this function can just return an &str, because the string will be somewhere inside the parameters, but on other platforms, it’ll have to allocate an extra string. What would be the best return type?

  1. Cow<str>
  2. String, and just use to_owned and the associated negligible performance hit.
  3. Some impl Trait shenanigans.
  4. Something else.
1 Like

Is this part of a public API to external users? Is this fn called on a fast/critical path or has a chance to be in the future? How big is the string?

1 Like

The API is public, the function will almost certainly be run on very, very cold paths, the strings are probably small (less than 256 bytes).

I assume caller is not likely to want to grow/shrink the string via mutations? I’d return a Cow<str> or a Box<str>, although it sounds like it really doesn’t matter performance wise. But I can’t think of any real downside to returning a Cow<str> and never thinking about this question again :slight_smile:.


Yeah, I’d go with Cow<str>, too. :smile: