String Benchmarks in C# - Refactoring for Speed/Maintainability

后端 未结 10 1423
无人及你
无人及你 2021-02-09 21:29

I\'ve been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler\'s book Refactoring: Improving the Design of Ex

10条回答
  •  梦谈多话
    2021-02-09 21:48

    Here is a slightly more optimal version. I have taken suggestions from previous posters, but also appended to the string builder in a block-wise fashion. This may allow string builder to copy 4 bytes at a time, depending on the size of the word. I have also removed the string allocation and just replace it by str.length.

        static string RefactoredMakeNiceString2(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder(str.Length);
            int start = 0;
            for (int i = 0; i < ca.Length; i++)
            {
                if (char.IsUpper(ca[i]) && i != 0)
                {
                    sb.Append(ca, start, i - start);
                    sb.Append(' ');
                    start = i;
                }
            }
            sb.Append(ca, start, ca.Length - start);
            return sb.ToString();
        }
    

提交回复
热议问题