2

I notice that I constantly need to do String::from("mydummystring") in Rust. Does the call to from() end up creating a full copy of the string data? Seems that would be a major performance issue.

trent
  • 25,033
  • 7
  • 51
  • 90
pdeva
  • 43,605
  • 46
  • 133
  • 171
  • 2
    Yes, it does, but you don't need to use an owned String if you don't need to mutate it. And if you do need to mutate it, you'd have to copy it out of .data segment as it will be marked read-only by the OS. – Ivan C Jan 30 '21 at 23:35
  • 1
    Something to keep in mind is Rust makes you very aware of when you're copying. In other words, "would be a major performance issue" compared to _what_? E.g. in C++ `void foo(const std::string&); foo("asd")` is gonna allocate and copy a string completely implicitly. Only recently did C++ even get a standard way to talk about non-owned strings in a...reasonable way (that's being generous). – GManNickG Jan 31 '21 at 07:18
  • The truly expensive operation is the heap application. It's among the most costly things we frequently do. The copy, while it may appear redundant is cheap in comparison, several orders in magnitude faster. – IInspectable Feb 02 '21 at 16:51

1 Answers1

7

Yes, From<&str> for String works by creating a new heap-allocated buffer and copying the data from the original slice into it.

Seems that would be a major performance issue.

Less than you'd think, probably. Copying a chunk of bytes is usually very fast. You should benchmark your code to know if copying is a bottleneck. Even when copying is slow, most non-trivial programs probably do some copying of strings; you can't just never copy anything.

Nevertheless, if there is a lot of unnecessary copying going on and it is a problem for your design, Rust offers plenty of other options. String is not Rust's only string type, or even the most frequently used one; if you don't need to copy strings, you can often borrow them using &str, share ownership using Rc<str>, defer the owning decision to runtime using Cow<str>, or even use a string interning library such as string-cache. Ownership and copying of values is under your control with Rust, much more so than with most other languages, in fact. Ultimately, it's up to you to choose what kind of ownership makes the most sense for strings in your program.

References

trent
  • 25,033
  • 7
  • 51
  • 90