Is there a benefit to explicit use of “new EventHandler” declaration?

前端 未结 4 1058
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 04:28

In assigning event handlers to something like a context MenuItem, for instance, there are two acceptable syntaxes:

MenuItem item = new MenuItem(         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 04:55

    Related to your edit - The adding of handlers isn't really affected by using new or not but there's a slight difference in removing handlers like this

    listView.ItemClick -= listView_ItemClick;
    

    and

    listView.ItemClick -= new ItemClickEventHandler(listView_ItemClick);
    

    albeit unlikely to affect most scenarios. The first version, without the new keyword, is supposedly more efficient.

    There's a detailed explanation in this post but the conclusion is

    So both works but which one should we use? If the events are subscribed/unsubscribed once at the beginning/end like in a typical WinForm application then it hardly matters. However if this is done multiple times then the second approach is preferable as it does less of costly heap allocations and will work faster

    (second approach in that post being the one without the new keyword)

    Having said that it seems like a micro optimization to me so it's unlikely to be a bottleneck in the majority of cases.

提交回复
热议问题