运行时的代码契约
据我读到的简而言之,代码契约可能会降低运行时性能。
是否可以在生产中禁用代码合约?
As far as I read in a nutshell book, code contracts could degrade the runtime performance.
Is it possible to disable code contracts in production?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
用户手册对此进行了相当详细的解释 - 那里是您可以拥有的各种选择。每个构建配置可以有不同的设置,在执行时检查合同,这不是“全有或全无”的选择 - 您可以根据可以在 Visual Studio 中调整的设置强制执行所有、部分合同或不执行合同。
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.
在我的博客上描述了我最喜欢的选项。
总结一下:
有些人更喜欢将先决条件包含在他们的发布版本中。如果通过 NuGet 分发,这尤其有用,因为它们不支持代码契约 dll。对于我的 NuGet 包,我正在迁移到在发布版本中包含先决条件,但也为“无先决条件的发布”构建单独下载。
I have my favorite options described on my blog.
To summarize:
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.
性能差异非常小,不会以明显的方式影响您的代码。除非你正在开发一些实时股票交易系统,否则我真的不会担心它。
至于在生产中禁用代码,我宁愿拥有代码契约的额外保护,而不是一些可能难以理解的错误。代码契约中的错误将准确地告诉您违反契约的位置和原因,而不是仅仅因为一些错误数据在调用堆栈树的 5 层中传递而必须深入挖掘某些深层调用堆栈。
@svanryckeghem 和@Stephen Cleary:
如果您正在使用或计划使用
Contract.Requires
并且不启用“运行时合约检查”,您将收到有关 IL 重写器 (ccrewrite.exe) 需要执行以下操作的运行时故障:受代码合同的使用的约束。然后,您将需要启用运行时合同检查才能使其正常工作。恕我直言,使用
Contract.Requires()
比Contract.Requires()
有用得多,因为您可以控制抛出的异常类型。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 thanContract.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.