Closed d-unsed closed 7 years ago
Method | Heap allocation* | Null-bytes check** |
---|---|---|
to_string |
✓ | ✓ |
to_string_unchecked |
✓ | ✗ |
to_str |
✗ | ✓ |
to_str_unchecked |
✗ | ✗ |
* heap allocation means that the contents of the original Ruby string are duplicated to a new heap-allocated Rust String
** null-bytes check means that before retrieving an underlying string from a Ruby string, MRI will perform a check for interior null bytes.
For example, running some_str.to_string()
on some_str = "Hello, \0World"
will raise an exception string contains null byte (ArgumentError)
.
Some quick benchmarks of these methods. I used MacBook Pro Mid 2014 (2.2 GHz Intel Core i7, 16 GB RAM), Ruby 2.4.0 and Rust 1.14.
(the more iterations per second the better)
to_str_unchecked()
has more or less constant throughput for any string length;to_string()
has the lowest throughput, because it does both heap allocation and null-bytes check;to_str()
performs better than to_string_unchecked()
on the strings shorter than 512 bytes (possibly, because heap allocation is more expensive than null-bytes checks for shorter strings);to_string_unchecked()
performs better than to_str()
on the strings longer than 512 bytes (possibly, because heap allocation is less expensive than null-bytes checks for longer strings);That is excellent, can't wait to see what difference it makes under real world circumstances.
RString::to_str(&self) -> &str
RString::to_str_unchecked(&self) -> &str
These methods are similar to
to_string()
andto_string_unchecked()
. The difference is that they return immutable references to underlying Ruby strings.The new methods do not allocate new
String
s on heap, thus they should be faster when a user just needs to get underlying data from Ruby string.