C# Interface Versus Virtual Method Performance

Performance optimization

Are interface calls faster than virtual ones? Sometimes when designing a type-based polymorphism layout in a C# program, you can choose between a base interface and a base class. If you use the interface, you can implement that interface as a contract. If you use the base class, you can declare virtual methods and then implement those methods on derived types.

This C# benchmark compares the performance of interface methods and virtual methods.

Example

Note

To start, this example program text written in the C# language is a benchmark harness that first declares a type that implements a method from an interface, and another type that implements a method matching a base class virtual method. The .NET 3.5 Framework was used for this benchmark. The two patterns are occasionally interchangeable in software projects.

Program that tests performance [C#]

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

Results. You can see, then, 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. Thus, we can surmise that replacing an interface-based type layout with a class-based, virtual method type layout would likely improve performance to some degree.

Answer: No, interface calls are not faster than virtual ones.

Summary

.NET Framework information

In this performance test, we discovered that interfaces have some level of performance impairment in the Common Language Runtime. Although both interface method invocations and virtual method calls inject another level of indirection, the runtime is able to more quickly cope with that added by virtual methods. Where possible, changing interfaces to base classes with virtual methods can improve performance of method invocations.

Interface Types
.NET