d-unsed / ruru

Native Ruby extensions written in Rust
MIT License
832 stars 40 forks source link

Get strings by reference #53

Closed d-unsed closed 7 years ago

d-unsed commented 7 years ago

These methods are similar to to_string() and to_string_unchecked(). The difference is that they return immutable references to underlying Ruby strings.

The new methods do not allocate new Strings on heap, thus they should be faster when a user just needs to get underlying data from Ruby string.

d-unsed commented 7 years ago

Methods

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).

Benchmarks

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.

string_benchmarks

(the more iterations per second the better)

Zapotek commented 7 years ago

That is excellent, can't wait to see what difference it makes under real world circumstances.