Friday, August 01, 2003

Why is IComparer an Interface?

Perhaps you are wondering why IComparer, which has only one method, Compare, is an interface and not a delegate? A delegate is much more versatile than an interface.

To answer that you need to look into one of .NET's dirty little secrets, delegate invocation performance. Jan Gray from the Microsoft CLR Performance Team has writen a great article that contains a table showing how much various IL operations take. A virtual call on his box executes in 5.4 ns. A delegate invoke takes 41 ns. (For reference, an integer add operation takes 1 ns.)

So there you go. If .NET designers had created IComparer as a delegate and not an interface, the performance of methods like Array.Sort would suffer tremendously and they would get pummeled in the benchmarks.

   2:04 PM

Content of this site is © Dejan Jelovic. All rights reserved.