Hacker News new | ask | show | jobs
by acqq 3396 days ago
Thanks!

I like Rust for what it does in advancing the state of the art of the languages, but I also like how this example demonstrates how hard it is to avoid "unsafe" constructs and remain competitive.

https://github.com/TeXitoi/benchmarksgame-rs/blob/master/src...

1 comments

For what it's worth, this alternate implementation has only one line of unsafe code (a call to the libc "memchr" function) and is only 9% slower than the fastest unsafe version:

https://github.com/mbrubeck/benchmarksgame-rs/blob/reverse_c...

It's very easy to write extremely fast safe Rust code. (The safe Rust version above is faster than the fastest C++ submission, on my computer.) Using "unsafe" for optimization is usually only helpful to get a few extra percent speedup in an inner loop. If this were production code rather than the benchmarks game, I'd probably ship the safe version.

Wonderful, thank you! Producing the safe versions which are that efficient is really the best argument for Rust that I can imagine.
As an update, this pull request now removes most of the unsafe code:

https://github.com/TeXitoi/benchmarksgame-rs/pull/46

Further update: I now have a Rust program that is 100% safe code and is also faster than any of the unsafe programs (including the C and C++ entries):

https://github.com/TeXitoi/benchmarksgame-rs/pull/55

> one line of unsafe code (a call to the libc "memchr" function)

Is burntsushi's Rust implementation of memchr notably slower than libc's?

The rust-memchr crate uses libc's memchr if it's available and known to be fast. Otherwise, it falls back to a pure Rust implementation (written by bluss, not me).

I expect this to change once we get SIMD. ;-)

> Is burntsushi's Rust implementation of memchr notably slower than libc's?

Not as far as I know. A lot of this benchmarksgame code has evolved slowly over time and hasn't been cleaned up yet to use "modern" crates and language features.