I understand that I should not optimize every single point of my program, let's just assume that I have to optimize array initialization.
So I wrote program that compares for loop
versus Array.Clear
using System;
using System.Diagnostics;
namespace TestArraysClear
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[100000];
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
sw.Reset();
sw.Start();
for (int j = 0; j < a.Length; j++)
{
a[j] = 0;
}
sw.Stop();
Console.WriteLine("for " + sw.ElapsedTicks);
sw.Reset();
sw.Start();
Array.Clear(a, 0, a.Length);
sw.Stop();
Console.WriteLine("Array.Clear " + sw.ElapsedTicks);
}
}
}
}
Output on my machine:
for 1166
Array.Clear 80
for 1136
Array.Clear 91
for 1350
Array.Clear 71
for 1028
Array.Clear 72
for 962
Array.Clear 54
for 1185
Array.Clear 46
for 962
Array.Clear 55
for 1091
Array.Clear 55
for 988
Array.Clear 54
for 1046
Array.Clear 55
So Array.Clear
is about 20 times faster than for loop
. But Array.Clear
initializes to 0
. Can I initialize array to -1
with the same perfomance somehow?
upd: I'm not looking for some "extreme unsafe" code. I'm looking for something as easy as Array.Clear
. I just wonder that .NET offers fast 0 initialization, but .NET doesn't offer initialization to other values. So why .NET like "0" much more than "-1"?
upd I want to reset existent array. So i'm looking for analog of Array.Clear
which will reset array to -1
, not 0