I wonder if it's a better practice to use :
var a = b.Substring(6);
Or
var a = b.Remove(0,6);
Which one is more efficient / faster ? Obviously substring has more options you can pick from but nothing that Remove() cant do.. Sorry if it's newbie question, I'm new to C#
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With