Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string.Substring() or string.Remove() [duplicate]

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#

like image 766
dB.Employee Avatar asked Dec 09 '15 20:12

dB.Employee


1 Answers

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;
}
like image 118
Kzrystof Avatar answered Oct 23 '22 00:10

Kzrystof