If you don't want to invest in a two-hour long video:
TL;DR:
Rails has a library, `ActiveSupport`, which adds methods to Ruby core classes. One of those methods is `String#blank?`, which returns a boolean (sometimes I miss this convention in Rust, the `?`) if the whole string is whitespace or not. It looks like this: https://github.com/rails/rails/blob/b3eac823006eb6a346f88793...
For fun, Yehuda tried to re-write `fast_blank` in Rust. Which looks like this:
extern crate libc;
mod buf; // a small buffer struct + impl, not shown
use buf::Buf;
#[no_mangle]
pub extern "C" fn tr_str_is_blank(b: Buf) -> bool {
let s = b.as_slice().unwrap();
s.chars().all(|c| c.is_whitespace())
}
Turns out, this implementation ends up being faster than that C one, while also being significantly more straightforward. This video is a two-hour dive into why that is.
1 comment
[ 4.9 ms ] story [ 19.7 ms ] threadTL;DR:
Rails has a library, `ActiveSupport`, which adds methods to Ruby core classes. One of those methods is `String#blank?`, which returns a boolean (sometimes I miss this convention in Rust, the `?`) if the whole string is whitespace or not. It looks like this: https://github.com/rails/rails/blob/b3eac823006eb6a346f88793...
It's pretty slow. So Discourse (which you may know from {users,internals}.rust-lang.org) uses the [`fast_blank`](https://rubygems.org/gems/fast_blank) gem, which provides this method via a C implementation instead. It looks like this: https://github.com/SamSaffron/fast_blank/blob/master/ext/fas...
For fun, Yehuda tried to re-write `fast_blank` in Rust. Which looks like this:
Turns out, this implementation ends up being faster than that C one, while also being significantly more straightforward. This video is a two-hour dive into why that is.