Reputation: 5604
Does too much usage of code contracts slows down the compilation process. Secondly code contracts are part of debug mode only what if i set code contracts and always compile the code in release mode, then will code contract work? i suppose it wont which means developer will be forced to work in debug mode and when you are creating a setup then make it in release mode. Am i right?
Upvotes: 2
Views: 1092
Reputation: 8019
Compilation is slowed down a bit because of the way that CodeContracts work. There is an IL re-writer that injects code into your methods based on the contracts that you specify. This happens after the C# compiler has come along and generated the IL for your assembly.
The runtime performance difference is quite small and will not affect your code in a noticeable way. Unless you are developing some real-time stock trading system, I seriously wouldn't even worry about it.
As far as disabling Code Contracts in Production, I would far rather have the added protection of Code Contracts that some possibly obscure error. An error in the code contract will tell you exactly where and why the Contract was violated as opposed to having to dig down in some deep call-stack just because some bad data was passed in 5 levels up the call-stack tree.
If you are using or are planning to use Contract.Requires<TException>
and do not enable 'Runtime Contract Checking', you'll get a runtime failure about the IL rewriter needing to be bound to the usage of Code Contracts. You will then be required to enable Runtime Contract Checking to get this to work.
IMHO, the use of Contract.Requires<TException>()
is far more useful than Contract.Requires()
since you have control over the type of exception thrown.
EDIT: One thing I forgot to add is that the IL Rewriter is completely independent of the C# compiler and there are no dependencies between the two.
Upvotes: 4
Reputation: 273244
Assuming Code Contracts from MS Devlab,
Compiling: The Contracts tools activate after your compile. There is a rewriter for the runtime checking, and that takes (a little) time as part of your build.
The static verifier runs after that, but in the background. You don't have to wait for it, unless you want to see the messages immediately.
Runtime behaviour. This is configurable in multiple steps, from fully Off (benchmark), Requires only / Requires+Ensures (release) to Full (analysis / debug).
Upvotes: 0