使用事件有多少性能开销? [英] How much performance overhead is there in using events?

查看:78
本文介绍了使用事件有多少性能开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程还很陌生,并且由于我对OOP的了解有限,因此决定使用事件在我的班级之间进行交流.自然,这将导致很多事件.

I am fairly new to programming and with my limited knowledge of OOP have decided to use events to communicate between my classes. Naturally, this will lead to quite a few events.

我想知道使用事件是否还有其他开销?我假设除非对事件进行处理(即,在类中有一个侦听器,该侦听器根据被触发的事件执行一个函数),否则实际上不会产生太大影响.但是我对C#中的事件不是很熟悉,只是想确认是否仅仅因为触发一个事件而存在大量额外的开销?

I wanted to know if there is any additional overhead to using events? I would assume that unless an event is acted upon (i.e, there is a listener in a class that executes a function based on the event being fired), then there shouldn't really be much of an impact. But I am not intimately familiar with events in C# and wanted to just confirm if there is significant extra overhead simply for firing off an event?

推荐答案

我想知道使用事件是否还有其他开销?我假设除非对事件进行处理(即,在类中有一个侦听器,该侦听器根据被触发的事件执行一个函数),否则实际上不会产生太大影响. B

I wanted to know if there is any additional overhead to using events? I would assume that unless an event is acted upon (i.e, there is a listener in a class that executes a function based on the event being fired), then there shouldn't really be much of an impact. B

通常,这是正确的.引发事件的标准模式只会检查调用列表以查看是否有订阅者,如果没有监听器则返回任何东西,这在大多数情况下在性能上将是很小的,并且可能不会一个问题.

In general, this is true. The standard pattern for raising an event will do nothing but check the invocation list to see if there are subscribers, and return if there are no listeners, which will be very minor in terms of performance in most cases, and is likely not going to be an issue.

即使有订阅者,使用事件的开销仍然相当小,因为它们通过委托调用有效地调用了订阅者处理程序,这仍然相对较快(尽管比直接方法调用慢).只要您不是在非常紧密的循环中执行此操作,它就可能微不足道.

Even when there are subscribers, the overhead of using events is still fairly minor, as they are effectively calling the subscribers handlers by a delegate invocation, which is still relatively fast (though slower than a direct method call). As long as you're not doing this in very tight loops, it's likely to be insignificant.

话虽如此,这和任何性能问题一样,可以归结为测量.如果没有针对您的情况进行实际衡量,就无法知道实际用法在实践中的重要性.为了确定在您的特定情况下这是否是合理的设计选择,您需要分析事件的使用情况,以确保这不是重要的问题.

That being said, this, like any performance question, boils down to measurement. Without actually measuring in your case, there's no way to know how significant the actual usage would be in practice. In order to know for certain whether this is a reasonable design choice in your specific case, you'd need to profile the usage of the events to make sure that it is not a significant issue.

这篇关于使用事件有多少性能开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆