In .NET, What Is Fastest Way to Initialize Multi-Dimensional Array to Non-Default Value

Posted by AMissico on Stack Overflow See other posts from Stack Overflow or by AMissico
Published on 2010-05-04T02:19:54Z Indexed on 2010/05/04 2:28 UTC
Read the original article Hit count: 333

How do I initialize a multi-dimensional array of a primitive type as fast as possible?

I am stuck with using multi-dimensional arrays. My problem is performance. The following routine initializes a 100x100 array in approx. 500 ticks. Removing the int.MaxValue initialization results in approx. 180 ticks just for the looping. Approximately 100 ticks to create the array without looping and without initializing to int.MaxValue. Routines similiar to this are called a few tens-of-thousands to several million times.

I am open to suggestions on how to optimize this non-default initialization of an array. One idea I had is to use a smaller primitive type when available. For instance, using byte instead of int, saves 100 ticks. I would be happy with this, but I am hoping that I don't have to change the primitive data type.

    public int[,] CreateArray(Size size) {
        int[,] array = new int[size.Width, size.Height];
        for (int x = 0; x < size.Width; x++) {
            for (int y = 0; y < size.Height; y++) {
                array[x, y] = int.MaxValue;
            }
        }
        return array;
    }

© Stack Overflow or respective owner

Related posts about .NET

Related posts about multidimensional-array