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
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