Benchmarking the following surprisingly gives better results for managed arrays( 10% faster, consistently ). I'm testing in Unity, so maybe it relates to Mono?
unsafe void Bench()
{
//Locals
int i, j;
const int bufSize = 1024 * 1024;
const int numIterations = 1000;
const float gain = 1.6745f;
float[] managedBuffer;
IntPtr ptr;
float * unmanagedBuffer;
Stopwatch stopwatch;
// Allocations
managedBuffer = new float[ bufSize ];
for( i = 0; i < bufSize; i++ )
{
managedBuffer[ i ] = UnityEngine.Random.value;
}
ptr = Marshal.AllocHGlobal( bufSize * sizeof( float ) );
unmanagedBuffer = ( float * )ptr.ToPointer();
Marshal.Copy( managedBuffer, 0, ptr, bufSize );
stopwatch = new Stopwatch();
stopwatch.Start();
// Unmanaged array iterations
for( i = 0; i < numIterations; i++ )
{
for( j = 0; j < bufSize; j++ )
{
unmanagedBuffer[ j ] *= gain;
}
}
UnityEngine.Debug.Log( stopwatch.ElapsedMilliseconds );
stopwatch.Reset();
stopwatch.Start();
// Managed array iterations
for( i = 0; i < numIterations; i++ )
{
for( j = 0; j < bufSize; j++ )
{
managedBuffer[ j ] *= gain;
}
}
UnityEngine.Debug.Log( stopwatch.ElapsedMilliseconds );
Marshal.FreeHGlobal( ptr );
}
I'm experimenting with unsafe code for an audio application which is quite performance critical. I'm hoping to increase performance and decrease / eliminate garbage collection.
Any insights appreciated!