Reputation: 13496
I have a structure (class) that keeps very large number of numbers (either float, double, int, byte) in an array.
Now I want to have very high performance approach to apply some primitive operations (Add/Subtract/Divide/Multiply with a constant) on this array.
This arrays is on a continuous piece of memory so for example for copying it I am using Buffer.BlockCopy.
But what about adding a constant or multiplying with a constant?
The first choice is to walk through the array using pointers. What other approaches do you suggest for this?
Upvotes: 4
Views: 4295
Reputation: 273244
Using pointer (unsafe) is not certain to be more performant.
Why don't you start with a normal for(int index = 0; index < data.Lenght; index++)
loop and see if it meets your requirements.
And of course, the next step would be processing in parallel :
Parallel.For(0, data.Length, i => data[i] *= myFactor);
Upvotes: 3
Reputation: 7931
This multiplies every element with 5 and writes back into the same array.
var someArray = new int[] {1, 2, 3, 4, 5, 6, 7};
int i=0;
Array.ForEach(someArray, (x) => {someArray[i++] = x * 5;});
Upvotes: 1
Reputation: 39089
Pointers won't help you much. Two approaches that could/should be combined:
If you want to reduce ("reduction") the result, e.g. say you want to build the sum of all elements, you could also divide the chunks recursively, and build sums of sums (of sums (of sums (you get the point))).
Upvotes: 1
Reputation: 3049
I don't think you will find a general solution faster than just walking through the array. Most processors will prefetch items in your array; thus as long as your manipulations are small, you'll obtain optimum performance by just accessing each item consecutively.
Keep work per item as straighforward as possible and minimize assignments and fetches inside the loop. Keep as much work as you can outside the loop.
Upvotes: 0