Fastest way to remove chars from string

前端 未结 7 1693
生来不讨喜
生来不讨喜 2020-12-05 13:52

I have a string from which I have to remove following char: \'\\r\', \'\\n\', and \'\\t\'. I have tried three different ways of removing these char and benchmarked them so I

7条回答
  •  半阙折子戏
    2020-12-05 14:29

    Here's the uber-fast unsafe version, version 2.

        public static unsafe string StripTabsAndNewlines(string s)
        {
            int len = s.Length;
            char* newChars = stackalloc char[len];
            char* currentChar = newChars;
    
            for (int i = 0; i < len; ++i)
            {
                char c = s[i];
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                        continue;
                    default:
                        *currentChar++ = c;
                        break;
                }
            }
            return new string(newChars, 0, (int)(currentChar - newChars));
        }
    

    And here are the benchmarks (time to strip 1000000 strings in ms)

        cornerback84's String.Replace:         9433
        Andy West's String.Concat:             4756
        AviJ's char array:                     1374
        Matt Howells' char pointers:           1163

提交回复
热议问题