问题描述
使用委托会减慢我的程序速度吗?
Does using delegates slow down my programs?
我一直在避开它们,因为我真的不知道它们是否会使我的程序变慢.我知道我是否会导致(捕获)异常,这会占用大量 CPU 资源,但我不知道委托和事件以及 .NET 对它们做了什么.
I've been avoiding them because I really have no clue if they make my programs any slower. I know if I cause a (catch) exception, that uses quite a bit of CPU power but I don't know about Delegates and Events and what .NET does to them.
推荐答案
代表非常非常快.不如直接方法调用快,但也不远.它们成为瓶颈的可能性微乎其微.
Delegates are very, very fast. Not quite as fast as direct method calls, but not far off. The chances of them becoming a bottleneck are miniscule.
(同样的例外情况,如果使用得当,实际上很少会导致性能问题.)
(Likewise exceptions, when used properly, rarely actually cause a performance issue.)
使用委托会让您的代码更简单、更易读、更健壮吗?如果是这样,请使用它们.仔细衡量你的表现,并密切关注它.仅当数据清晰时才为了性能而远离可读性.
Would using delegates make your code simpler, more readable, and more robust? If so, use them. Measure your performance carefully, and keep an eye on it. Move away from readability for the sake of performance only when the data is clear.
我确信有一些图表显示了委托、接口和非虚拟方法调用的速度等等——我不知道它们在哪里,但如果你真的担心的话,你总是可以自己运行测试.
I'm sure there are some graphs around showing the speed of delegates vs interfaces vs non-virtual method calls etc - I don't know where they are, but you could always run tests yourself if you're really worried.
这篇关于使用委托会减慢我的 .NET 程序的速度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!