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;
}
}
}