7

I'll try to clarify my question :

I have a function called Draw (which someone (XNA) calls her 60 times per second), and i have many objects to draw, so i have the following code : void Draw() { obj1.draw(); obj2.draw(); obj3.draw(); .... }

Is there will be a performance impact if instead i will create an event, which will be raised by Draw(), and all the objects would sign up for the event ?

In case i wansn't clear what i'm asking is : Does a call to a function by signing up to an event is different from a regular call ?

OopsUser
  • 4,642
  • 7
  • 46
  • 71
  • 2
    I can't comment on the performance, but it sounds like switching to the event-driven system would drastically improve the maintainability of your code and is certainly a better design. – Cᴏʀʏ Dec 13 '12 at 21:20
  • Also, event handlers usually run on threads of their own. Function calling runs on the same thread. Since you are talking of drawing, which i assume would involve UI manipulation, you need to be careful with this. – Ravi Y Dec 13 '12 at 21:24
  • 3
    @ryadavilli I'm certain event handlers do NOT fire in their own thread if you fire them normally. Event handlers are executed sequentially on the current thread. – Maarten Dec 13 '12 at 21:31

2 Answers2

7

Regarding performance, I think Jon Skeet's example is pretty conclusive that delegates don't add any significant overhead to performance, and may even improve it.

One factor you do need to consider with events/delegates is handling unhooking objects listening to an event or your reference counts will not reset properly and you would find yourself with memory leaks. Avoid anonymous methods unless you're prepared to store references to them so they can be unwired on Dispose etc.

Community
  • 1
  • 1
Steve Py
  • 26,149
  • 3
  • 25
  • 43
4

The ildasm shows that a direct call of function is performed with "call method" command, while call through event performed with "callvirt delegatename::Invoke()". May seem that direct call should be faster, but let's consider what is Invoke(). Invoke is not a member of Delegate or MulticastDelegate classes. It's a special method generated by compiler

.method public hidebysig virtual instance void 
            Invoke(string s) runtime managed
{
}

This method doesn't contain any implementation, that might looks strange. But if we pay attention on "runtime" specificator, magic will dissipates. The "runtime" means that code will be generated at runtime, and as we know, it will happens only once. So theoretically both should be the same in terms of productivity.

As for Jon Skeet's test, I launch it several times and interchange direct call with call with the help of delegate, and didn't get confirmation that delegates improve perfomance. Sometimes delegates won, sometimes direct call won. I think that it's because of GC or something else inside .NET affects test, or just switching processes by Windows.

Nikita Nesterov
  • 426
  • 2
  • 5