I'm writing a Rust program which will create some immutable struct values,
which are, the struct values that won't change after being initialized.
For these values, there are multiple ways to represent them. They can be represented
directly by themselves, by Box
of them, by Rc
of them and by Arc
of them.
Also, there are a lot of representations of immutable strings, including Box<str>
, String
, Rc<str>
, Arc<str>
and bytes::Bytes
.
So I decide to do a benchmark to find out which representation has the best performance under certain situation.
You can download the criterion result from releases.
Through analysis, I found:
- For struct, heap allocation overhead is too much. Even using
Box
orArc
might reduce a little moving or cloning overhead, it's not worth it. - For strings,
Arc
andRc
requires an extra clone which results in slower construction. However if the string will be cloned,Arc
andRc
is often faster.Bytes
creation is cheap but cloning cost a bit more than plainArc
. - For the string which has length of 128, the overhead difference is less than
100ns
, so if the string is not super-long or won't be cloned for many times, optimizing for zero-cost might not worth it.
A optimized Arc<String>
.