ReverseString, a C# interview-question

前端 未结 12 1847
予麋鹿
予麋鹿 2021-01-31 06:15

I had an interview question that asked me for my \'feedback\' on a piece of code a junior programmer wrote. They hinted there may be a problem and said it will be used heavily o

12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-31 07:08

    The problem is that string concatenations are expensive to do as strings are immutable in C#. The example given will create a new string one character longer each iteration which is very inefficient. To avoid this you should use the StringBuilder class instead like so:

    public string ReverseString(string sz)
    {
        var builder = new StringBuilder(sz.Length);
        for(int i = sz.Length-1; i>=0; i--)
        {
          builder.Append(sz[i]);
        }
        return builder.ToString();
    }
    

    The StringBuilder is written specifically for scenarios like this as it gives you the ability to concatenate strings without the drawback of excessive memory allocation.

    You will notice I have provided the StringBuilder with an initial capacity which you don't often see. As you know the length of the result to begin with, this removes needless memory allocations.

    What normally happens is it allocates an amount of memory to the StringBuilder (default 16 characters). Once the contents attempts to exceed that capacity it doubles (I think) its own capactity and carries on. This is much better than allocating memory each time as would happen with normal strings, but if you can avoid this as well it's even better.

提交回复
热议问题