Search code examples
c#.netperformanceportabilityunchecked

Does using unchecked context hurt performance or portability in C#?


I want to implement a fast hash function that will use int datatype and rely on integer overflow. MSDN says that in order to guarantee that overflows don't trigger exceptions I have to use unchecked blocks for that code.

Suppose I surround only that computation in an unchecked block. Will my code have any performance or portability problems because of that?


Solution

  • Technically only the checked blocks should slow. So I don't think an unchecked block (a block where the framework has to do less checks) could slow. It isn't a context switch or something similar. The JIT simply doesn't emit instructions to check for overflow/underflow. Now, clearly if someone created a "special" processor where overflow must be simulated and ported Mono on it, or where an overflow causes different results than on Intel processors, an unchecked block would be slower (because the JIT would have to "simulate" it). But note that the base types of .NET are defined in the ECMA standard. Signed ints must be based on two-complement for example, and their size must be 8, 16, 32, 64 bits. There isn't much space for "strange" processors that use 36 bits integers.