Introduction
How would you implement a Max() method that returns the maximum value element in the array of int values? Well, the most obvious approach would be to iterate through the array and compare each element to the so far max value. And this is 100% correct. However, there is another way to do the same with significantly better performance. The faster approach can be implemented thanks to the concept of the vectorization (SIMD – Single Instruction Multiple Data is referred to as vectorization where operations are applied to all of the elements in a “vector” at the same time – as mentioned here). We can achieve such a vectorization by using e.g. the Vector struct.
Alright, enough talk, it’s benchmark time!
Benchmark
I prepared an extension method:
public static class VectorizationExtension
{
public static int Max_Vectorized(this IEnumerable<int> source)
...
The following benchmark results show how the Max_Vectorized
method performs in comparison to the Max
extension method provided by the LINQ.
As you can see the the Max_Vectorized
method performance is amazing! So here is the question, if the Vector-based Max method is so much faster, why it is not used in LINQ then? Well, it is, but in .NET 7!
If you compare .NET 7 results you can see that the Max
method is roughly as fast as Max_Vectorized
method. At this point I have no idea why the Max_Vectorized
is faster as it’s based on the same concept but it’s probably because of the advanced level of theMax
method implementation (see the implementation here).
Summary
To sum up, vectorization is a powerful way to improve the performance in some cases. It is definitely good to know that .NET has a support of Vectors as some hot paths may require to speed them up by using this little trick. I highly recommend to look at the Performance Improvements in .NET 7 (or at least some part of this huuuge document) as it’s a great reference in terms of further experiments and searches.
As always I’ve prepared an example and you can find it on my github, project: Vectorization, test project: Vectorization-tests, benchmark project: Vectorization-benchmark.
Have a nice day, bye!
Be First to Comment