Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two-dimensional array when I am adding values by column it write very slowly (less than 300x):

class Program
    {
        static void Main(string[] args)
        {
            TwoDimArrayPerfomrance.GetByColumns();
            TwoDimArrayPerfomrance.GetByRows();
        }
    }

    class TwoDimArrayPerfomrance
    {

        public static void GetByRows()
        {
            int maxLength = 20000;
            int[,] a = new int[maxLength, maxLength];
            DateTime dt = DateTime.Now;
          
            Console.WriteLine("The current time is: " + dt.ToString());

            //fill value
            for (int i = 0; i < maxLength; i++)
            {
                for (int j = 0; j < maxLength; j++)
                {

                    a[i, j] = i + j;
                }
            }


            DateTime end = DateTime.Now;
            Console.WriteLine("Total: " + end.Subtract(dt).TotalSeconds);

        }

        public static void GetByColumns()
        {
            int maxLength = 20000;
            int[,] a = new int[maxLength, maxLength];
            DateTime dt = DateTime.Now;
            Console.WriteLine("The current time is: " + dt.ToString());
            for (int i = 0; i < maxLength; i++)
            {
                for (int j = 0; j < maxLength; j++)
                {

                    a[j, i] = j + i;
                }
            }
            DateTime end = DateTime.Now;
            Console.WriteLine("Total: " + end.Subtract(dt).TotalSeconds);

        }

    }

The Column vice taking around 4.2 seconds while Row wise taking 1.53


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is the "cache proximity" problem mentioned in the first comment. There are memory caches that any data must go through to be accessed by the CPU. Those caches store blocks of memory, so if you are first accessing memory N and then memory N+1 then cache is not changed. But if you first access memory N and then memory N+M (where M is big enough) then new memory block must be added to the cache. When you add new block to the cache some existing block must be removed. If you then have to access this removed block then you have inefficiency in the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...