Throwing an exception is c开发者_如何学编程ostly in terms of writing good performance code. But what about raising an event? Hence this theoretical querstion to the .net clr crowd:
What are the memory implications concerning raising an event with one subscriber? With 1 000 000 subscribers? How to calculate these implications? Does raising one event euqal calling a member method of (the otherwise handler) subscriber directly?"Raising an event" usually just means "calling a delegate" - but potentially a multicast delegate with many invocations in its list. Each of these is pretty cheap... not much more than a direct method call usually, although there are situations which are more expensive. (IIRC, call a delegate which has been created via an interface method is more expensive.)
I strongly recommend that you write the most natural code to start with, and then test it to see if it performs well enough. I can't immediately think of a quicker way to effectively call a bunch of subscriber methods. I suspect it's generally as cheap as iterating over a list of interface implementations and calling an interface method on each, and it may well be significantly cheaper in some situations.
The main implication is that you can not control the implications if you make the event public. Any subscriber can take an hour to process your event, block indefinitely or might even throw you an exception. Usually this lack of control is not a big problem, since either you have control over all subscribers yourself or you are creating a component to be used by others and then the users of your component are responsible for the usage and the event handlers they subscribe.
Raising an event would be about the same performance as calling the same number of methods as the subscription count.
精彩评论