C# string.Substring() or string.Remove()
Looking at the code using reflector, InternalSubString
is doing only one wstrcpy
whereas Remove
is doing two of them. My guess would be the first one(SubString
) is a tad faster.
Here is the code for the Remove
method of the string class:
public unsafe string Remove(int startIndex, int count)
{
//...
string text = string.FastAllocateString(num);
fixed (char* ptr = &this.m_firstChar)
{
fixed (char* ptr2 = &text.m_firstChar)
{
string.wstrcpy(ptr2, ptr, startIndex);
string.wstrcpy(ptr2 + (IntPtr)startIndex, ptr + (IntPtr)startIndex + (IntPtr)count, num - startIndex);
}
}
}
And the code called by the SubString
method:
private unsafe string InternalSubString(int startIndex, int length)
{
string text = string.FastAllocateString(length);
fixed (char* ptr = &text.m_firstChar)
{
fixed (char* ptr2 = &this.m_firstChar)
{
string.wstrcpy(ptr, ptr2 + (IntPtr)startIndex, length);
}
}
return text;
}
Substring
is faster based on this post:
Fastest way to remove first char in a String
"I do check now by call each one about 90000000 and I go the following result:
Remove
: 06.63 - TrimStart
: 04.71 - Substring
: 03.09 so from result Substring
is the best" - @Amr Badawy