开发者

Code Contracts at runtime

As far as I read in a nutshell book, code contracts could degrade the runtime performance.

Is it possible to disable code co开发者_JAVA百科ntracts in production?


The user manual explains this in a fair amount of detail - there are all kinds of options you can have. Each build configuration can have different settings for which contracts are checked at execution time, and it's not an "all or nothing" choice - you can enforce all, some or none of the contracts, based on settings which can be tweaked in Visual Studio.


I have my favorite options described on my blog.

To summarize:

  • In Release mode, I recommend unchecking Perform Runtime Contract Checking but selecting to Build the Contract Reference Assembly. This will place Preconditions in a separate dll which your clients can optionally use (if they check Call-site Requires Checking), but removes all overhead if they don't check that option.
  • In Debug mode, set Perform Runtime Contract Checking to Full.

Some people prefer Preconditions to be included in their Release build. This is particularly useful if distributing via NuGet because they don't support Code Contract dlls. For my NuGet packages, I'm migrating towards including Preconditions in the Release builds, but also having a separate download for a "Release without Preconditions" build.


The 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 the code in Production, I would far rather have the added protection of Code Contracts instead of 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.

@svanryckeghem and @Stephen Cleary: 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 (ccrewrite.exe) 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.


In your project properties, go to Code Contract, select the "Release" Configuration and uncheck runtime checking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜