views:

262

answers:

1

I have a project where I want to have checked arithmetic by default, except for one performance sensitive spot. Unfortunately, VB.Net doesn't have an 'unchecked' block.

Ideally the framework would have some sort of integer type with explicitly unchecked arithmetic, but I didn't find anything like that. I did find that expression trees have binary expressions for unchecked operations, but the delegate overhead cancels out the unchecked advantage (and then some).

Currently I'm converting the inputs to UInt64/Int64 before doing the arithmetic, then converting back (with a bitwise And to ensure in-range). It's about 50% slower than unchecked arithmetic (according to profiling).

Moving the arithmetic-sensitive part to a project with unchecked arithmetic might work, but it seems like overkill to give it an assembly all to itself.

+2  A: 

Personally, I think leaving this in its own assembly, especially since it'll be such a small assembly, is a good option. This makes maintenance easier, since it's easy to regenerate this assembly at any time. Just make a separate assembly flagged unchecked, and put your performance-sensitive code there.

Reed Copsey
You can do unchecked arithmetic in VB. The problem is that it's a project-wide option (under Advanced Compile Options in the Compile tab).
Strilanc
@Strilanc: Even better - edited my answer, then. I'd just make a separate project for your perf. critical code, and reference it, then.
Reed Copsey
I did something slightly different: I wrote types with unchecked arithmetic and put those in the unchecked assembly. Now I have ModByte/ModInt16/ModInt32/ModInt64 and the unchecked assembly definitely won't slowly absorb code.
Strilanc