I am working on some applications that require very low latency and repeatedly load memory and do some checks on how, for example, allocating an ad-hoc list against pre-allocating and clearing the list. I expected test runs to allocate memory in advance to run much faster, but to my surprise they are actually a bit slower (when I skip the test for 10 minutes, the average is about 400 ms).
Here is the test code I used:
class Program
{
private static byte[] buffer = new byte[50];
private static List<byte[]> preAlloctedList = new List<byte[]>(500);
static void Main(string[] args)
{
for (int k = 0; k < 5; k++)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
List<byte[]> list = new List<byte[]>(300);
for (int j = 0; j < 300; j++)
{
list.Add(buffer);
}
}
sw.Stop();
Console.WriteLine("#1: " + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
for (int j = 0; j < 300; j++)
{
preAlloctedList.Add(buffer);
}
preAlloctedList.Clear();
}
sw.Stop();
Console.WriteLine("#2: " + sw.Elapsed);
}
Console.ReadLine();
}
}
Now, which is really interesting, I ran the perfton side by side and saw the following template, which looks exactly as I expected:
Collection Green = Gen 0
Blue = allocated bytes / sec
Red =% Time in GC
# 1 # 2

, : # 1 , # 2?
, Test # 2 , , GC .., # 1 ?
List.Clear() ?
,
Tom
, , GC , # 2
