I saw this article recently while exploring various ways to work with images at a pixel-level.
http://www.codeproject.com/Articles/16403/Fast-Pointerless-Image-Processing-in-NET
And the author mentions that
What of the performance cost of using a managed array instead of pointers? Wouldn’t using a managed array be slower than using pointers? It might surprise you, but based on my tests, the answer is no. In my tests, have found that the array method is at least 10% faster than the pointer method.
My first attempt at working with images at a pixel level was using the GetPixel/SetPixel methods, which was incredibly slow. Then I was directed to this link and it was considerably faster.
I haven’t tried the method described in the article but can anyone support it? Or perhaps it is only faster under certain conditions?
That depends quite a bit on how you are accessing the arrays.
If you are using the length of the array in a loop, the compiler recognises this and knows that it doesn’t have to check the bounds of the index, as the loop itself makes it impossible for the index to be out of bounds. This way of accessing arrays will be close in performance to using pointers.
If you are accessing the array with an arbitrary index, the compiler has to add the code that checks the bounds of the index, which will add a few instructions to every access. This way of accessing arrays will be slower than using pointers.
It also depends on how efficient the code is that uses pointers. In the end a pointer is always used to access the array data even if you are using an index to access the array, so it’s always possible to write pointer code that is at least as efficient as the code accessing the array by index.
Also, it depends on how much processing you are doing. Using marshalling to move the data from and to an image means that you move all the data twice already. If you are doing little processing, that can never be as fast as accessing the data in place.
Note: The method used to marshal the data in the article only works if the
Stridevalue is positive. If the image is stored upside down in memory (common for Bitmap files), then theStridevalue is negative, and the calculated data size will be negative.