简体   繁体   中英

2D array vs 1D array

I have read the question for Performance of 2-dimensional array vs 1-dimensional array

But in conclusion it says could be the same (depending the map own map function, C does this automatically)?...

I have a matrix wich has 1,000 columns and 440,000,000 rows where each element is a double in C# ...

If I am doing some computations in memory, which one could be better to use in performance aspect? (note that I have the memory needed to hold such a monstruos quantity of information)...

If what you're asking is which is better, a 2D array of size 1000x44000 or a 1D array of size 44000000, well what's the difference as far as memory goes? You still have the same number of elements, In the case of performance and understandability. the 2D is probably better, Imagine having to manually find each column or row in a 1D array. when you know exactly where they are in a 2D array.

It depends on how many operations you are performing. In the below example, I'm setting the values of the array 2500 times. Size of the array is (1000 * 1000 * 3). The 1D array took 40 seconds and the 3D array took 1:39 mins.

var startTime = DateTime.Now;
Test1D(new byte[1000 * 1000 * 3]);
Console.WriteLine("Total Time taken 1d = " + (DateTime.Now - startTime));

startTime = DateTime.Now;
Test3D(new byte[1000,1000,3], 1000, 1000);
Console.WriteLine("Total Time taken 3D = " + (DateTime.Now - startTime));

public static void Test1D(byte[] array)
{
    for (int c = 0; c < 2500; c++)
    {
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = 10;
        }
    }
}

public static void Test3D(byte[,,] array, int w, int h)
{
    for (int c = 0; c < 2500; c++)
    {
        for (int i = 0; i < h; i++)
        {
            for (int j = 0; j < w; j++)
            {
                array[i, j, 0] = 10;
                array[i, j, 1] = 10;
                array[i, j, 2] = 10;
            }
         }
     }
}

The difference between double[1000,44000] and double[44000000] will not be significant.

You're probably better of with the [,] version (letting the compiler(s) figure out the addressing. But the pattern of your calculations is likely to have more impact (locality and cache use).

Also consider the array-of-array variant, double[1000][] . It is a known 'feature' of the Jitter that it cannot eliminate range-checking in the [,] arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM