Throwing exceptions in .NET is far more expensive than most developers realize. When a throw occurs, the CLR captures a full stack trace, allocates on the heap, unwinds stack frames, and generates EH metadata — making exceptions orders of magnitude slower than normal control flow. A BenchmarkDotNet comparison of three approaches (no exception, exception-based, and OneOf<T>) demonstrates the performance and memory cost at 10% failure rate across 100,000 iterations. The OneOf<T> discriminated union pattern, using struct value types, avoids heap allocations and stack unwinding entirely. The post provides clear guidance on when to use each approach: exceptions for truly unexpected/environmental failures and programming bugs, and Result/OneOf for business rule rejections, validation failures, API errors, and high-throughput paths.

2 Comments

Sort: