5 ms·
Good point, but C++ exceptions are expensive because they allow you to jump back multiple stack frames at once. If in Rust you're going to check every return va
by amelius 6y ago
Good point, but C++ exceptions are expensive because they allow you to jump back multiple stack frames at once. If in Rust you're going to check every return value, then isn't that more expensive on average?
- steveklabnik 6y agoI don't have a great handle on the exact details, but my suspicion is that this kind of analysis is hard to do, because it can play out differently in the micro vs macro. That is, in a naive implementation, yes, but after the compiler is done inlining and DCE-ing and yadda yadda yadda things end up looking differently in real codebases than one might assume. I do believe there's been some discussions in C++ land about the relative performance of these approaches, though I can't find good references right this second.
- Ericson2314 6y agoThere are more branches, but the branch predictor should be able to figure it out. Someday we should push multiple return points, one for each enum variant of the return type, and then we avoid the branches too. (This approach is described in https://www.ccs.neu.edu/home/shivers/papers/mrlc-jfp.pdf https://www.ccs.neu.edu/home/shivers/papers/mrlc-jfp.pdf ).
- Rusky 6y agoThat would be neat, but it's not a pure win. It's more just a different set of trade-offs, because it defeats the CPU's return address stack predictor. For exception-like Result enums where you want to predict the Ok variant every time that's probably fine (as long as your CPU is new enough that taking the error path won't cause it to mispredict every return afterwards), but it may or may not be a win in the general case of enum returns.
- saurik 6y agoYou are also just wasting fast storage--often a register--tracking and checking this stuff (at least for any type for which there isn't a natural invalid value, such as a null pointer); multiple return points is going to do the same thing, but worse, as you will need to hand the second return point to the called function but will no longer be able to reuse invalid return values.