【问题标题】:C# string.Substring() or string.Remove() [duplicate]C# string.Substring() 或 string.Remove() [重复]
【发布时间】:2016-03-15 06:25:47
【问题描述】:

我想知道使用它是否更好:

var a = b.Substring(6);  

或者

var a = b.Remove(0,6);  

哪个更高效/更快?显然 substring 有更多选项可供您选择,但 Remove() 没有什么不能做的。对不起,如果这是新手问题,我是 C# 新手

【问题讨论】:

  • 子字符串在从字符串 heh 中获取子字符串方面更有意义
  • 那么两者之间没有区别吗?他们在相同的时间内完成相同的工作?
  • 实际上,我很确定 Substring 会返回一个包含前 6 个字符的新字符串.. remove 会返回一个没有前 6 个字符的字符串...
  • 测试一下。阅读文档。除非您对性能进行分析并发现您在其中一种方法上花费了大量时间,否则不必担心性能。
  • 使用清楚地表达意图的任何东西。这两者之间应该没有太大区别,即使有区别也可以忽略不计。

标签: c# string substring


【解决方案1】:

Substring 基于这篇文章更快:

Fastest way to remove first char in a String

“我现在通过调用每个大约 90000000 进行检查,结果如下:

Remove: 06.63 - TrimStart: 04.71 - Substring: 03.09 所以从结果来看Substring 是最好的” - @Amr Badawy

【讨论】:

  • 我不会太相信这个基准。这可能是真的,但我们并不真正知道该基准是如何执行的。
【解决方案2】:

字符串实例是不可变的 - 如果返回值不同,Substring()Remove() 都将分配一个新字符串,如果不是,则返回相同的字符串,如本例所示。 Substring 更好地反映了意图,并且应该是首选 - 几乎总是,最好让代码易于理解而不是担心微小的性能差异。

【讨论】:

    【解决方案3】:

    查看使用反射器的代码,InternalSubString 只执行了一个 wstrcpyRemove 正在执行其中两个。我猜第一个(SubString)会快一点。

    这里是字符串类的Remove方法的代码:

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

    以及SubString方法调用的代码:

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

    【讨论】:

    • string.Remove(int) 也是这样吗?
    • @Deantwo Remove(int) 只是调用Substring(0, int)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 2014-01-02
    • 2013-03-02
    相关资源
    最近更新 更多