Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize array to -1 fast? [duplicate]

Tags:

c#

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

like image 655
Oleg Vazhnev Avatar asked Dec 01 '25 05:12

Oleg Vazhnev


1 Answers

There's probably a way to do it via unmanaged arrays (pointers) to set the contiguous block of memory to the same value (e.g. whatever the int '-1' is when mapped into its 4-bytes of memory).

This article here discusses a faster method than with a managed for loop (example given is a byte[] array): http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html

Also, here: What is the equivalent of memset in C#?

As other posters have mentioned, it seems a bit extreme to do this though, and normally the speed required to initialise the array using a for loop would not be a problem.

like image 139
dodgy_coder Avatar answered Dec 03 '25 19:12

dodgy_coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!