Delegate parameters


Let's say you have two delegates at hand:


delegate void DummyDelegateWithInt(int x);


and


delegate void DummyDelegateWithObject(object x);


Everything seems OK right? But how about the performance issues? that question just crossed my mind. int is a value type where object is a reference type. I just implemented a very simple application that makes method calls through these delegates and passes the parameter 0 (int::zero). Of course these method calls are made more than once, 1,000,000,000 times... here is the result:


Method calls made through the first delegate takes 6.3 - 6.4 seconds (1,000,000,000 times), and the second one takes 32 - 33 seconds in average. Of course you may have a much faster CPU than I have, but it will not change the fact will it?

Comments (6)
  1. luisguerrero18@hotmail.com says:

    That’s right Murat, this is because when you call second delegate dotnet framework have to boxed int parameter, so boxing it’s painful for performance. It’s simple.

  2. oldnewthing says:

    Unfair comparison. The second one has to box the integer a billion times. Instead, box the integer once and pass the boxed integer a billion times; that should be a more fair comparison.

  3. Asztal says:

    Agreed that it is unfair comparison, but because this situation will never really occur.

    You can indeed box it just once if you’re just calling the method with the same object a billion times, but if you are doing anything non-trivial (e.g. you have a IEnumerable<int> and you want to call the delegate on each item in the list), you’ll still have to box them all).

    Of course, at that point, the overhead of boxing might prove to be far less significant than the overhead of enumeration, which might me doing something computationally expensive like calculating prime numbers. But you might as well just use the delegate that doesn’t require boxing, if you can.

  4. muratkar says:

    In fact this situation occurs in events. The first parameter of the EventHandler delegate is always of type "object" in the framework, and any developer may have as many as possible number of listeners attached to this event.

  5. oldnewthing says:

    Oh, okay. The context was missing (“The signature of the delegate is determined by some outside entity but I want to pass an int.”) As originally written, it appeared to be a comparison between two delegate signatures as in “Look, objects are slower than integers!”

  6. Can Erten says:

    First, welcome to blogging space! I was waiting for you….

    I think it is fair enough though. .NET should have  all the generic libraries before everyhing else. Thanks to parametric functions anyway 🙂

    On the other hand this is the only sample that dynamic languages can do benchmarks…

Comments are closed.

Skip to main content