How to quickly initialize an array to -1?

I understand that I should not optimize every point of my program, let's say that I need to optimize the initialization of the array.

So I wrote a program that compares for loopversusArray.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.Clearabout 20 times faster than for loop. But Array.Clearinitialized 0. Can I initialize an array to -1with the same success?

upd: I'm not looking for some kind of "extreme unsafe" code. I am looking for something as simple as Array.Clear. I'm just curious that .NET offers quick initialization of 0, but .NET does not offer initialization to other values. So why is .NET like "0" so much more than "-1"?

upd reset . Array.Clear, reset array -1, 0

+3
4

, (), (, , int '-1' 4- ).

, ( byte []): http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html

, : memset #?

, , , , for, .

+5

, - :

int[] a = {-1, -1, -1, -1, ...}

,

var sb = new StringBuilder("int[] a = {");
for (int i = 0; i < 10000; ++i)
    sb.append(i != 10000 -1 ? "-1," : "-1");
sb.append("};");
+2

, , .

int[] a = Enumerable.Range(0, 100000).Select(s => -1).ToArray();

UPDATE:

int[] a = Enumerable.Repeat(-1, 100000).ToArray();
+2

- . .

Crazy theory - it could be faster than an Clear()array if this method was implemented in unmanaged code. But notice @JeffMercado's comment on larger sample sizes.

0
source

All Articles