Search code examples
c#.netstringoptimizationstringbuilder

Ways to improve string memory allocation


This question is more theoretical than practical, but still.

I've been looking for a chance to improve the following code from the string memory allocation standpoint:

/* Output for n = 3:
*
*  '  #'
*  ' ##'
*  '###'
*
*/
public static string[] staircase(int n) {
    string[] result = new string[n];

    for(var i = 0; i < result.Length; i++) {
        var spaces = string.Empty.PadLeft(n - i - 1, ' ');
        var sharpes = string.Empty.PadRight(i + 1, '#');

        result[i] = spaces + sharpes;
    }

    return result;
}

PadHelper is the method, that is eventually called under the hood twice per iteration.

So, correct me if I'm wrong, but it seems like memory is allocated at least 3 times per iteration.

Any code improvements will be highly appreciated.


Solution

  • StringBuilder is always an answer when it comes to string allocations; I'm sure you know that so apparently you want something else. Well, since your strings are all the same length, you can declare a single char[] array, populate it every time (only requires changing one array element on each iteration) and then use the string(char[]) constructor:

    public static string[] staircase(int n)
    {
        char[] buf = new char[n];
        string[] result = new string[n];
    
        for (var i = 0; i < n - 1; i++)
        {
            buf[i] = ' ';
        }
    
        for (var i = 0; i < n; i++)
        {
            buf[n - i - 1] = '#';
            result[i] = new string(buf);
        }
    
        return result;
    }