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

断了今生、忘了曾经 提交于 2020-06-25 01:36:51

问题


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#


回答1:


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



回答2:


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




回答3:


String instances are immutable - both Substring() and Remove() will allocate a new string if the return value is different, and will return the same string if it's not, as in this case. Substring better reflect the intent, and should be preferred - almost always, it's better to make the code easily understandable than to worry about minute performance differences.



来源:https://stackoverflow.com/questions/34187988/c-sharp-string-substring-or-string-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!