Recently I had the good fortune to get a good look at the Rust codebase. Fun times!
One thing I noticed is that there are many places where owned
Strings are used, even though in the majority of cases, a
&'static str would suffice. Many of those strings are just allocated to be used in
format!ting or to be written out somewhere.
Since I am a fan of
Cows, I wonder why we don't use them in the compiler more often? So I wrote a microbenchmark to see how the performance differs. The results? Allocating is very fast, but just using a Cow is even faster (to the tune of 2ns per
Cow vs. 33ns per allocation, this benchmark does not include e.g. cache effects, so the actual effect is likely underreported).
So, Rust developers, next time you reach for a
.to_owned() or worse,
.to_string(), consider using
(Of course, this likely has little effect on the actual runtime of the compiler, because those strings are usually not on hot code paths. Still, with allocation you never know if you tread on other code's toes).