简体   繁体   中英

Performance difference between generic and non generic method

Let's say for the sake of the example that we want to work on linear algebra, with different type of matrices. And that we have a custom Matrix class that implements :

interface IMatrix
{
    double this[int i, int j] { get; set; }
    int Size { get; }
}

I want to implement Matrix multiplication. I was under the impression that both methods :

static void Multiply<TMatrix>(TMatrix a, TMatrix b, TMatrix result) where TMatrix : IMatrix

and

static void Multiply(Matrix a, Matrix b, Matrix result)

(with similar implementation of course) Would internally produce the exact same IL and hence the same performances. It is not the case : the first one is four times slower than the second one. Looking at the IL, it seems the generic one is similar to a call through interface :

static void Multiply(IMatrix a, IMatrix b, IMatrix result)

Am I missing something ? Is there any way to get the same performances with generics than with a direct call ?


Installed Framework 4.8, Target Framework : 4.7.2 (also tested with .Net Core 3)

Method implementation :

static void Multiply(Matrix a, Matrix b, Matrix result)
{
    for (int i = 0; i < a.Size; i++)
    {
        for (int j = 0; j < a.Size; j++)
        {
            double temp = 0;
            for (int k = 0; k < a.Size; k++)
            {
                temp += a[i, k] * b[k, j];
            }
            result[i, j] = temp;
        }
    }
}

Minimal reproductible example

.NET will only generate code for a generic method once for all reference types. And that code must call through the IMatrix interface, as the various implementing types might implement the interface with different methods. So it simply is an interface call.

However if you make Matrix a struct instead of a class the JITter will generate a type-specific implementation of the generic methods, and in that the interface call can be optimized away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM