gpt4 book ai didi

c# - 使用事件有多少性能开销?

转载 作者:太空狗 更新时间:2023-10-29 17:33:13 25 4
gpt4 key购买 nike

我对编程还很陌生,而且我对 OOP 的了解有限,因此决定使用事件在我的类之间进行通信。自然,这会导致很多事件。

我想知道使用事件是否有任何额外开销?我假设除非对事件采取行动(即类中有一个监听器根据被触发的事件执行函数),否则实际上不会有太大影响。但我对 C# 中的事件不是很熟悉,只是想确认是否仅仅为了触发一个事件而产生显着的额外开销?

最佳答案

为了防止多年后有人偶然发现这个问题,我使用了 BenchMarkDotNet 框架来衡量事件调用所需的时间。我区分了 1 个订阅者和 100 个订阅者。

使用的测试代码:

private event EventHandler TestEventSingle;
private event EventHandler TestEventMultiple;

public OtherTests()
{
TestEventSingle += OtherTests_TestEvent;

for (int i = 0; i < 100; i++)
{
TestEventMultiple += OtherTests_TestEventMultiple;
}
}

private void OtherTests_TestEventMultiple(object sender, EventArgs e)
{
//Do something with the event...
}

private void OtherTests_TestEvent(object sender, EventArgs e)
{
//Do something with the event...
}

[Benchmark]
public void InvokeEvent()
{
TestEventSingle.Invoke(this, null);
}
[Benchmark]
public void InvokeEventMore()
{
TestEventMultiple.Invoke(this, null);
}
[Benchmark]
public void CallMethod()
{
OtherTests_TestEvent(this, null);
}
[Benchmark]
public void CallMethodMore()
{
for (int i = 0; i < 100; i++)
{
OtherTests_TestEventMultiple(this, null);
}
}

测试结果:

<表类="s-表"><头>方法均值错误标准偏差<正文>调用事件1.6774 纳秒0.0246 纳秒0.0230 纳秒调用事件更多192.2076 纳秒3.6115 纳秒3.3782 纳秒调用方法0.0317纳秒0.0106 纳秒0.0099 纳秒调用方法更多37.1203 纳秒0.4147 纳秒0.3676 纳秒

关于c# - 使用事件有多少性能开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com