Fill a multidimensional array with same values C#

Fill a multidimensional array with same values C#

dynamic two dimensional array in c#
c# loop through multidimensional array
c# multidimensional array get row
c# multi-dimensional array length
c# array of arrays
populate a two dimensional array c#
how to add values to two dimensional array in c#
multidimensional array in c#

Is there a faster way of doing this using C#?

double[,] myArray = new double[length1, length2];

for(int i=0;i<length1;i++)
    for(int j=0;j<length2;j++)
        myArray[i,j] = double.PositiveInfinity;

I remember using C++, there was something called memset() for doing these kind of things...


A multi-dimensional array is just a large block of memory, so we can treat it like one, similar to how memset() works. This requires unsafe code. I wouldn't say it's worth doing unless it's really performance critical. This is a fun exercise, though, so here are some benchmarks using BenchmarkDotNet:

    public class ArrayFillBenchmark
    {
        const int length1 = 1000;
        const int length2 = 1000;
        readonly double[,] _myArray = new double[length1, length2];

        [Benchmark]
        public void MultidimensionalArrayLoop()
        {
            for (int i = 0; i < length1; i++)
            for (int j = 0; j < length2; j++)
                _myArray[i, j] = double.PositiveInfinity;
        }

        [Benchmark]
        public unsafe void MultidimensionalArrayNaiveUnsafeLoop()
        {
            fixed (double* a = &_myArray[0, 0])
            {
                double* b = a;

                for (int i = 0; i < length1; i++)
                for (int j = 0; j < length2; j++)
                    *b++ = double.PositiveInfinity;
            }
        }

        [Benchmark]
        public unsafe void MultidimensionalSpanFill()
        {
            fixed (double* a = &_myArray[0, 0])
            {
                double* b = a;
                var span = new Span<double>(b, length1 * length2);
                span.Fill(double.PositiveInfinity);
            }
        }

        [Benchmark]
        public unsafe void MultidimensionalSseFill()
        {
            var vectorPositiveInfinity = Vector128.Create(double.PositiveInfinity);

            fixed (double* a = &_myArray[0, 0])
            {
                double* b = a;

                ulong i = 0;
                int size = Vector128<double>.Count;

                ulong length = length1 * length2;
                for (; i < (length & ~(ulong)15); i += 16)
                {
                    Sse2.Store(b+size*0, vectorPositiveInfinity);
                    Sse2.Store(b+size*1, vectorPositiveInfinity);
                    Sse2.Store(b+size*2, vectorPositiveInfinity);
                    Sse2.Store(b+size*3, vectorPositiveInfinity);
                    Sse2.Store(b+size*4, vectorPositiveInfinity);
                    Sse2.Store(b+size*5, vectorPositiveInfinity);
                    Sse2.Store(b+size*6, vectorPositiveInfinity);
                    Sse2.Store(b+size*7, vectorPositiveInfinity);
                    b += size*8;
                }
                for (; i < (length & ~(ulong)7); i += 8)
                {
                    Sse2.Store(b+size*0, vectorPositiveInfinity);
                    Sse2.Store(b+size*1, vectorPositiveInfinity);
                    Sse2.Store(b+size*2, vectorPositiveInfinity);
                    Sse2.Store(b+size*3, vectorPositiveInfinity);
                    b += size*4;
                }
                for (; i < (length & ~(ulong)3); i += 4)
                {
                    Sse2.Store(b+size*0, vectorPositiveInfinity);
                    Sse2.Store(b+size*1, vectorPositiveInfinity);
                    b += size*2;
                }
                for (; i < length; i++)
                {
                    *b++ = double.PositiveInfinity;
                }
            }
        }
    }

Results:

|                               Method |       Mean |     Error |    StdDev | Ratio |
|------------------------------------- |-----------:|----------:|----------:|------:|
|            MultidimensionalArrayLoop | 1,083.1 us | 11.797 us | 11.035 us |  1.00 |
| MultidimensionalArrayNaiveUnsafeLoop |   436.2 us |  8.567 us |  8.414 us |  0.40 |
|             MultidimensionalSpanFill |   321.2 us |  6.404 us | 10.875 us |  0.30 |
|              MultidimensionalSseFill |   231.9 us |  4.616 us | 11.323 us |  0.22 |

MultidimensionalArrayLoop is slow because of bounds checking. The JIT emits code each loop that makes sure that [i, j] is inside the bounds of the array. The JIT can elide bounds checking sometimes, I know it does for single-dimensional arrays. I'm not sure if it does it for multi-dimensional.

MultidimensionalArrayNaiveUnsafeLoop is essentially the same code as MultidimensionalArrayLoop but without bounds checking. It's considerably faster, taking 40% of the time. It's considered 'Naive', though, because the loop could still be improved by unrolling the loop.

MultidimensionalSpanFill also has no bounds check, and is more-or-less the same as MultidimensionalArrayNaiveUnsafeLoop, however, Span.Fill internally does loop unrolling, which is why it's a bit faster than our naive unsafe loop. It only take 30% of the time as our original.

MultidimensionalSseFill improves on our first unsafe loop by doing two things: loop unrolling and vectorizing. This requires a CPU with Sse2 support, but it allows us to write 128-bits (16 bytes) in a single instruction. This gives us an additional speed boost, taking it down to 22% of the original. Interestingly, this same loop with Avx (256-bits) was consistently slower than the Sse2 version, so that benchmark is not included here.

But these numbers only apply to an array that is 1000x1000. As you change the size of the array, the results differ. For example, when we change the array size to 10000x10000, the results for all of the unsafe benchmarks are very close. Probably because there are more memory fetches for the larger array that it tends to equalize the smaller iterative improvements seen in the last three benchmarks.

There's a lesson in there somewhere, but I mostly just wanted to share these results, since it was a pretty fun experiment to do.

Multidimensional Arrays, This example declaration creates a two-dimensional array of four rows 7, 8 } }; // A similar array with string elements. string[,] array2Db = new� Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and each row has 4 columns. int [,] a = new int [3,4] { {0, 1, 2, 3}, /* initializers for row indexed by 0 */ {4, 5, 6, 7}, /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ };


I wrote the method that is not faster, but it works with actual multidimensional arrays, not only 2D.

public static class ArrayExtensions
{
    public static void Fill(this Array array, object value)
    {
        var indicies = new int[array.Rank];

        Fill(array, 0, indicies, value);
    }

    public static void Fill(Array array, int dimension, int[] indicies, object value)
    {
        if (dimension < array.Rank)
        {
            for (int i = array.GetLowerBound(dimension); i <= array.GetUpperBound(dimension); i++)
            {
                indicies[dimension] = i;
                Fill(array, dimension + 1, indicies, value);
            }
        }
        else
            array.SetValue(value, indicies);
    }
}

[Solved] how to populate a 2D array in C#?, Hide Expand Copy Code. // random integer returned can include this value private const int randMinimum = 0; // note that random integer� As discussed in the previous chapter, Arrays in C# will support multi-dimensional arrays. In c#, a multidimensional array is an array that contains more than one dimension to represent the elements in a tabular format like rows and columns. In c#, multidimensional arrays can support either two or three-dimensional series.


double[,] myArray = new double[x, y];

if( parallel == true )
{
    stopWatch.Start();
    System.Threading.Tasks.Parallel.For( 0, x, i =>
    {
        for( int j = 0; j < y; ++j )
            myArray[i, j] = double.PositiveInfinity;  
    });
    stopWatch.Stop();
    Print( "Elapsed milliseconds: {0}", stopWatch.ElapsedMilliseconds );
}
else
{
    stopWatch.Start();
    for( int i = 0; i < x; ++i )
        for( int j = 0; j < y; ++j )
          myArray[i, j] = double.PositiveInfinity;  
    stopWatch.Stop();
    Print("Elapsed milliseconds: {0}", stopWatch.ElapsedMilliseconds);
}

When setting x and y to 10000 I get 553 milliseconds for the single-threaded approach and 170 for the multi-threaded one.

C# - Multidimensional Arrays, Initializing Two-Dimensional Arrays. Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and� Array Initialization. See also. Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns. C#. int[,] array = new int[4, 2]; The following declaration creates an array of three dimensions, 4, 2, and 3.


visual c# .net - multi dimensional arrays, How to set up and use multi-dimensional arrays in C# Net. that fills a 2- dimensional array with the values in the table above: C# .NET Code to fill a Multi Dimensional Array See if you can get the same values as ours, in the form below: C# . A multi-dimensional array is just a large block of memory, so we can treat it like one, similar to how memset() works. This requires unsafe code. This requires unsafe code. I wouldn't say it's worth doing unless it's really performance critical.


C# 2D Array Examples, In this 2D world, an element is addressed with X and Y. Consider now C#. The word rank is the same concept as "dimension" in that a 2D array has 2 ranks,� C# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. C# supports multidimensional arrays, which are arrays of arrays. You can pass to the function a pointer to an array by specifying the array's name without an index.


C# Multidimensional Arrays: 2D, 3D & 4D, C# supports multidimensional arrays up to 32 dimensions. The multidimensional The following access values of the two-dimensional array. Example: Access� This will create an array of 10 integers with each element of the array having value 0 (the default value of type int). To create an array initialized with a non-default value, we can use Enumerable.Repeat from the System.Linq Namespace: To create a bool array of size 10 filled with "true" bool[] booleanArray = Enumerable.Repeat(true, 10