Using an unsafe
array in C# allows you to get direct pointers to the elements (if they are of intrinsic types). This should provide a performance benefit because there are no range checks to be done of each access. I know you said no unsafe code, but if you want performance you have to consider this option.
Consider the example below:
public unsafe class PinnedArray : IDisposable
{
byte[] values;
byte* pointer;
GCHandle handle;
public PinnedArray(int size)
{
values=new byte[size];
handle=GCHandle.Alloc(values, GCHandleType.Pinned);
pointer=(byte*)handle.AddrOfPinnedObject().ToPointer();
}
~PinnedArray()
{
Dispose();
}
public void Dispose()
{
if(values!=null)
{
handle.Free();
values=null;
}
}
// This is fast because it uses pointers
public void AddFrom(PinnedArray other)
{
if(values.Length!=other.values.Length)
{
throw new ArgumentException("other");
}
for(int i = 0; i<values.Length; i++)
{
pointer[i]+=other.pointer[i];
}
}
public void FillRandom()
{
Random rand = new Random();
for(int i = 0; i<values.Length; i++)
{
values[i]=(byte)(rand.Next()%256);
}
}
}
class Program
{
static void Main(string[] args)
{
var A = new PinnedArray(100);
var B = new PinnedArray(100);
B.FillRandom();
A.AddFrom(B);
}
}
With my testing I see a 20% speedup in doing math using pointers (pointer[i]
) as opposed to array access (value[i]
).
PS. This declaration comes from Microsoft. In their parallel toolkit examples there is a project named Strassens
which benchmarks matrix multiplication and uses the above scheme for quick math.
8
solved How to directly access objects in array with C# (without using unsafe)? [closed]