You’d think trying save .NET CLR from constantly allocate memory on the heap for a new array would give save you some ticks here or there. Maybe give the garbage collector a break from finding all these thrown away array instances on the heap.
Lemme give you the surprising anti-climax. It is not statistically significant.
NEW vs REUSE
Iterations new byte[] reuse difference(ms) 1 x 10000 1594ms 1094ms 500 2 x 10000 2656ms 2093ms 563 3 x 10000 3250ms 3344ms -94 4 x 10000 4125ms 4359ms -234 5 x 10000 5172ms 5141ms 31 6 x 10000 6391ms 6172ms 219 7 x 10000 7422ms 7203ms 219 8 x 10000 8453ms 8203ms 250 9 x 10000 9453ms 9641ms -188
If it was, wouldn’t the difference get bigger as there are more iterations? One test gets a new reference to a byte[] each time. The other copies the same reference to a byte[] from a static variable.
Don’t be fooled by the increasing numbers with increasing iterations. That’s the test filling with random data. It’s the difference between the 2 that matters. So it would seem, there is very little to be gained by avoid instantiating new arrays, for the cost of trying to figure out where the hell is “__buffer” declared.
static void Main(string[] args)
{
Random rnd = new Random(Environment.TickCount);
int START_SIZE = 10000;
int SAMPLES = 10;
int[] a = new int[SAMPLES];
int[] b = new int[SAMPLES];
Console.WriteLine("New byte[] array each loop");
for (int j = 1; j < SAMPLES; j++)
{
var size = START_SIZE* j;
var start1 = Environment.TickCount;
for (int i = 0; i < size; i++)
{
byte[] buffer = new byte[START_SIZE];
rnd.NextBytes(buffer);
}
a[j] = Environment.TickCount - start1;
Console.WriteLine("iterations={0}, {1}ms", size, a[j]);
}
Console.WriteLine("reusing byte[] array");
__buffer = new byte[START_SIZE];
for (int j = 1; j < SAMPLES; j++)
{
var size = START_SIZE * j;
var start1 = Environment.TickCount;
for (int i = 0; i < size; i++)
{
var buffer = __buffer;
rnd.NextBytes(buffer);
}
b[j] = Environment.TickCount - start1;
Console.WriteLine("iterations={0}, {1}ms", size, b[j]);
}
Console.WriteLine("NEW vs REUSE");
for (int j = 1; j < SAMPLES; j++)
{
Console.WriteLine("{0} x {1} \t{2}ms \t{3}ms \t{4}", j, START_SIZE, a[j], b[j], a[j]- b[j]);
}
Console.ReadLine();
}
static byte[] __buffer;