ylliX - Online Advertising Network
Vertex AI - Antrophic and Mistral models: Why does it require Imegen access?

What’s the fastest way to perform element-wise addition and read a column in a multi-dimensional array in C#?


I’ve inherited a codebase using multi-dimensional arrays (of sizes in the thousands) in a performance-critical path. In particular, the code wants to read off columns from the array and also perform element-wise addition by columns. I don’t really want to re-write a lot of logic to switch rows and columns just so I can use Span<T> on a row, but it would be easy to swap out the multi-dimensional array for something else if it improves performance. Using the latest and greatest .NET techniques there must be a better way to do this, right?

public IEnumerable<double> SliceColumn(double[,] array, int index)
{
    for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
    {
        yield return array[i, index];
    }
}

public void AddColumn(double[,] array, int index, double[] other)
{
    for (int i = 0; i != array.GetLength(0); i++)
    {
        array[i, index] += other[i];
    }
}

I’ve had a look into Span2D<T> and/or TensorPrimitives but it’s still not obvious to me – could anybody show how to improve the above code please?



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *