Sunday, 17 March 2013

Array Resizing Optimization


Optimizing your C# code is fundamental for improving your Application's Performance and Scalability.

Here, we'll know the performance optimization involved when we explicitly specify an approximate size of the C# collection during its declaration.



When you declare a collection, an arbitrary memory chunk is reserved for that variable. Consider a List of strings variable. The initial size/capacity is set as 2 by the Dot Net framework. As and when the number of strings in the list reach the maximum capacity, the size allocated to the list of strings variable doubles. Whenever there's a doubling of memory-reservation for a variable, there's a minor delay when the CLR in the background does its job. After all, dynamically increasing the memory size during run-time has a time-cost associated to it.

Consider a list of strings having 1000 values in it. If this variable is declared without any approximate size specification, there'll be 10 resizings of that collection. Even specifying that you fairly think the variable will hold more that 300 values in it reduces the resizing only to 2! This will easily give you a performance boost of 10-30 % depending on the collection you are resizing.

Please check out this video link where I go through this topic in more detail.

C# Experiments: Array Resizing Optimization




The code typed-in during the tutorial is as follows for your reference:-

            Stopwatch s = Stopwatch.StartNew();
            //var lst = new List<int>();
            var lst = new List<int>(1000);

            int numberOfResizes = 0;
            HashSet<long> capacities = new HashSet<long>();

            for (int i = 0; i < 1000000; i++)
            {
                capacities.Add(lst.Capacity);
                lst.Add(i);
            }

            numberOfResizes = capacities.Count;

            s.Stop();
            MessageBox.Show(Convert.ToString(s.ElapsedMilliseconds) + " milliseconds");

Thank you for reading this post and watching the video. Please Subscribe, Comment and Rate the channel if you liked the video.


Goto C# Experiments to access more of such content! Thanks again!