I've created a lower triangular distance matrix (because of size issues) as jagged array Note: Distances between objects are symmetric
var dm = new double[size][]
for (var i = 0; i < size; i++)
{
dm[i] = new double[i+1];
for (var j = 0; j < i+1; j++)
{
dm[i][j] = distance(data[i], data[j]);
}
}
I need to access this matrix very often so I made the following method for it
private double GetValueOfDM(int row, int column, double[][] dm)
{
return column <= row ? distanceMatrix[row][column] : distanceMatrix[column][row];
}
With the Visual Studio performance analysis one sees the major speed issue lies in the only row of the GetValueOfDM
method.
Has someone a good idea how to speed this up?
You could remove the conditional in the method and increase memory usage to increase access performance like so:
Now that you don't have a conditional, the compiler can remove a branch prediction. Also, you should run tests with your actual use cases to ensure that it is actually going to be a problem. Analysis would probably reveal that a branching conditional will be the slowest part of your code, but it doesn't necessarily mean that it's actually going to slow anything down noticeably. In addition, you could try running it in Release mode (with compiler optimizations) to see how it affects performance.
If you are on a system where you don't have the memory available to double the size of the array, then the code you have is probably close to optimal for accessing a jagged array.