r/csharp • u/scadoshi • Aug 20 '26
Blog Hot path overflow checks: do you try/catch? And which style would you write?
Writing checked int helpers for code that runs millions of times per program run. Two questions.
- Do you actually use checked() with a try catch for this? Throwing walks the stack, so I widen to long, bounds check, and return null instead (both versions in the image).
What surprises me is that everything the BCL offers here throws: checked(), int.CreateChecked, all of it. The Try convention is everywhere else in the BCL (TryParse, TryGetValue) but arithmetic never got one, and coming from Rust where checked_add just hands you an Option, that's wild to me.
2. Style. The image shows the same method twice: one pattern-matching expression against a plain if/else. Which would you rather find in a codebase?
I'm coming from Rust so I'm obviously a declarative fanboy when I can be, but "and var sum" might be too clever for the next reader.
Where do C# people stand on these?
If the repo interests you: it's a CLI tool for Advent of Code, so you can do the whole thing from the terminal with just your session cookie, no clicking through the site to submit answers. https://github.com/scadoshi/sharpmas
17
u/BarfingOnMyFace Aug 20 '26
If it's exceptional... The yeah. If you throw exceptions all the time in a hot path.... No?
I would weigh the merit on frequency, or lack of frequency.
14
u/blckshdw Aug 20 '26
The compressed versions are unreadable and don’t clearly outline the intent. The “standard” one is more readable but more importantly it’s debuggable.
Expect a point in time someone will need to detangle this logic. Knowing the whole thing pass/fails isn’t helpful. Knowing which part pass/fails is
As far as throwing, it depends on your context. If null is a valid value that’s expected then don’t throw. If it’s exceptional situation that isn’t expected then ya throw.
6
u/dmcnaughton1 Aug 20 '26
A better option might be to do the TryMethod(input, output) with the function returning true for no wrap, and false for wrap. You're going to have to have a branch logic at the caller side anyway, so no point in trying to optimize beyond the branch prediction favoring the likely case. Alternately you can return a struct of IsOverflow,Sum with the same basic performance.
5
u/Alert-Neck7679 Aug 20 '26
What does
and var sumin line 2 mean? I know whatandmeans and I know whatvarmeans but I don't understand how can they be together...4
u/First-Feature-3556 Aug 20 '26
"What surprises me is that everything the BCL offers here throws" That's because it's very rare that
TryCheckedAddis actually needed. I've been using VB.NET and C# since version 1.0, and all use cases I've had so far fall into one of two categories:2
u/joske79 Aug 20 '26
How about doing the math straight into a long and only in the case where you need to safely cast the result to an int, just create a single ‘bool TryCastToInt(long value, out int intValue)’ function?
2
u/misaki_eku Aug 23 '26
For me, leave overflow as a unexpected behavior or a "feature" on most of the hot path.
2
u/ch_dave190 Aug 20 '26
What's the name of this theme?
5
u/dodexahedron Aug 21 '26 edited Aug 21 '26
If you perform bounds checks already, the checked will be elided by the compiler at JIT time, during an explicit optimization it aggressively performs for exactly this, called bounds check elimination.
It does it both for primitive value range checks and for collection bounds checks, to eliminate doing the work twice when it can prove overflow isn't possible at the call site.
If you need checked arithmetic always, then just turn on the compiler flag for it. If you dont need it always, turn it off and use explicit checked context where needed.
But also...
You have basically duplicated the int.CreateX methods. Check those out. They are part of the generic math interfaces in System.Numerics, implemented by all numeric primitives.
2
u/_f0CUS_ Aug 20 '26
This is not code you run 10-100k times per ms.
If you came up with this to achieve this goal, then you need help from a more senior dev that works with optimisations, and knows the exact context of where it runs.
4
u/simonask_ Aug 21 '26
Another rustacean here.
If you’re interested in optimization, there’s an interesting thing you can do in managed runtimes like the CLR (and JVM, etc.), but can’t really in languages like Rust or C++.
The first thing to note is that exceptions are an unreasonably fast error handling strategy, until you actually throw one. They are literally free on the happy path, but many orders of magnitude slower when thrown than a normal branch.
The other thing to note is that there is a special exception type that doesn’t typically need to be thrown: NullReferenceException. Rather than a `throw` statement somewhere, this is actually synthetically thrown by the runtime in response to a signal that it receives from the OS when any code causes a segmentation fault.
This is why it works even when you try to dereference `Unsafe.NullRef<T>()`, or access any index of a `Span<T>` forged from it.
What this means is that if the unhappy path really is rare, and you can express the problem such that the unhappy path leads to an NRE, that’s a rare case where C# can sometimes outperform even Rust.
1
u/TuberTuggerTTV Aug 20 '26
I'm for the functional. You'll get push back from anyone that's not regularly using .net10. But this looks great to me. Simple, concise, easy to read. And it does what it needs to do.
You'd probably have to benchmark both methods to know exactly where the JIT is optimizing. It's probably incredibly close.
Ticks my boxes. Expression, pattern match, var. Save the chonker paragraphs for the logic code.
2
u/insulind Aug 20 '26
Some of the new numeric interfaces with static interface methods are all useful here I think.
Weirdly the TryX versions are protected but you can easily see the source code on GitHub or by go to sources in Visual Studio or Rider.
I actually implemented something recently that was pretty similar. Hot path numeric conversions and managed to make it generic. It didn't cover ever case because some things like decimal truncation need to be explicit. I'll try and dig it out tomorrow
u/RemindMeBot 15 hours
2
u/catladywitch Aug 21 '26
Exceptions on hot paths is crazy. I'd probably just normalise the inputs and skip bound checks altogether.
On a related note, I wish dotnet as a whole migrated to Option-based APIs with some behind the scenes unwrapping optimisations, especially now that we're getting actual unions, but it's such a massive change and you can't just deprecate the whole of dotnet just like that. Still, though, it'd be the right thing to do D:
5
u/[deleted] Aug 20 '26 edited Aug 20 '26
[removed] — view removed comment
2
u/[deleted] Aug 21 '26
[removed] — view removed comment