二维数组的快速不安全访问

本文关键字:不安全 访问 二维数组 | 更新日期: 2023-09-27 18:13:26

我有一个巨大的二维数组。我需要从中获得元素,但我有一个问题-它非常慢(我认为从编译器检查索引的问题)。我怎么能得到我的数组元素不安全?

private byte[][] MY_TASTE_ARRAY;
for (int d = 0; d < MANY_TIMES; d++)
{      
   int a = MY_TASTE_ARRAY[first_index][second_index];
   MakeSomethingWitha(a);
}

二维数组的快速不安全访问

数组访问并不慢,我尝试了这个程序,比较了从0到255的一堆连续循环数字的求和时间,或者直接将它们放在锯齿数组或矩阵中:

        const int N = 10000;
        var jagged = new byte[ N ][];
        var matrix = new byte[ N, N ];
        var count = (byte)0;
        for (var i=0; i< N;  i++ )
        {
            jagged[ i ] = new byte[ N ];
            for ( var j = 0; j < N; j++ )
            {
                jagged[ i ][ j ] = count;
                matrix[ i, j ] = count;
                count = count == 255 ? 
                    (byte) 0 : 
                    (byte) ( count + 1 );
            }
        }
        var watch = new Stopwatch();
        watch.Start();
        var total = 0;
        for ( var i = 0; i < N; i++ )
        {
            for ( var j = 0; j < N; j++ )
            {
                total += jagged[ i ][ j ];
            }
        }
        watch.Stop();
        Console.WriteLine( "Total with jagged array: {0} in {1} ms", total, watch.ElapsedMilliseconds );
        watch.Restart();
        total = 0;
        count = (byte)0;
        for ( var i = 0; i < N; i++ )
        {
            for ( var j = 0; j < N; j++ )
            {
                total += matrix[ i, j ];
            }
        }
        watch.Stop();
        Console.WriteLine( "Total with matrix: {0} in {1} ms", total, watch.ElapsedMilliseconds );
        watch.Restart();
        total = 0;
        count = (byte)0;
        for ( var i = 0; i < N; i++ )
        {
            for ( var j = 0; j < N; j++ )
            {
                total += count;
                count = count == 255 ?
                    (byte)0 :
                    (byte)( count + 1 );
            }
        }
        watch.Stop();
        Console.WriteLine( "Total without array: {0} in {1} ms", total, watch.ElapsedMilliseconds );

和结果是497毫秒使用锯齿数组,624毫秒使用矩阵和486毫秒直接计算数字。