Re:Using unwrap() in Rust is okay
by burntsushi on Monday August 08, 2022 @02:56PM
(#32389479)
Yes. I work on regex engines. Here's the code with all the crazy checks that return errors that can never happen:
And here's a search (I ran it a few times):
Here's code that's safe that will panic when there's a bug:
And here's a search with it:
So that's 10% right there. We can keep going though. Let's get rid of the bounds checks. We have to use unsafe though. The stakes have risen. Now if there's a bug, we probably won't get a panic. Instead we get UB. Which might lead to all sorts of bad stuff.
And now the same search:
For a smaller gain.
[ Parent
| on HN ]
Re:Using unwrap() in Rust is okay
by fatherzine on Monday August 08, 2022 @03:19PM
(#32389784)
This is so awesome, thanks for sharing! I am happy that the "~10% perf hit" intuition is reasonably close to what the data shows. What is the right tradeoff? I am not an author of widely popular regex engines, so I'll leave that evaluation to more qualified people.
Re:Using unwrap() in Rust is okay
by burntsushi on Monday August 08, 2022 @05:02PM
(#32390969)
10% is an excellent win. And given that I consider the first code snippet to be effectively nonsense, the right trade off is obvious to me. :)
I bet if me and you sat down with a big codebase side-by-side, I could convince you that the style you're proposing is totally unworkable.
Now, whether it's worth it to use unsafe and elide bounds checks is harder. The gain I showed here is small, but it can be bigger in other examples. It depends. But it is certainly less clear. It helps that this is probanly the easiest kind of unsafe to justify, because you just have to make sure the index is in bounds. Other types of unsafe can be quite tricky to justify.