C# Interface Performance

Performance optimization

Are interface calls faster than virtual ones? If we use an interface, we implement that interface as a contract. If we use a base class, we declare virtual methods and then implement those methods on derived types.

Virtual

Example

Virtual keyword

This example program is a benchmark harness. It first declares a type that implements a method from an interface. It also declares a type that implements a method matching a base class virtual method.

Note:The .NET 3.5 Framework was used for this benchmark. The two patterns are occasionally interchangeable in software projects.

C# program that tests performance

using System;
using System.Diagnostics;

interface IInterfaceExample
{
    void Y();
}

class ImplementsInterface : IInterfaceExample
{
    public void Y()
    {
    }
}

class BaseExample
{
    public virtual void Y()
    {
    }
}

class DerivesBase : BaseExample
{
    public override void Y()
    {
    }
}

class Program
{
    const int _max = 100000000;
    static void Main()
    {
	IInterfaceExample interface1 = new ImplementsInterface();
	BaseExample base1 = new DerivesBase();
	interface1.Y();
	base1.Y();

	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    interface1.Y();
	}
	s1.Stop();
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    base1.Y();
	}
	s2.Stop();
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.Read();
    }
}

Output

3.21 ns
2.24 ns
Interface

You can see that this test shows that an interface method invocation is somewhat slower than a virtual method call. The interface call takes over 3 nanoseconds, while the virtual method call takes over 2 nanoseconds.

Therefore, we surmise that replacing an interface-based type layout with a class-based, virtual method type layout would likely improve performance. Interface calls are not faster.

Summary

Framework: NET

Interfaces have some level of performance impairment. Both interface method invocations and virtual method calls inject another level of indirection. But the runtime is able to more quickly cope with that added by virtual methods.

Tip:Where possible, changing interfaces to base classes with virtual methods can improve performance of method invocations.


C#: Interface