删除字符串中第一个字符的最快方法

发布于 2024-09-10 01:29:21 字数 283 浏览 5 评论 0原文

假设我们有以下字符串

string data= "/temp string";

如果我们想删除第一个字符 / 我们可以通过很多方法来做到这一点,例如:

data.Remove(0,1);
data.TrimStart('/');
data.Substring(1);

但是,我真的不知道哪个有最好的算法并这样做更快..
有一个是最好的还是都一样?

Say we have the following string

string data= "/temp string";

If we want to remove the first character / we can do by a lot of ways such as :

data.Remove(0,1);
data.TrimStart('/');
data.Substring(1);

But, really I don't know which one has the best algorithm and doing that faster..
Is there a one that is the best or all are the same ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

ㄟ。诗瑗 2024-09-17 01:29:21

第二个选项确实与其他选项不同 - 如果字符串是“///foo”,它将变成“foo”而不是“//foo”。

第一个选项比第三个选项需要更多的工作来理解 - 我认为 Substring 选项是最常见和可读的。

(显然,它们中的每一个作为单独的语句都不会做任何有用的事情 - 您需要将结果分配给一个变量,可能是 data 本身。)

我不会在这里考虑性能,除非这实际上对你来说是一个问题 - 在这种情况下,你知道的唯一方法就是拥有测试用例,然后很容易为每个选项运行这些测试用例并比较结果。我希望 Substring 可能是这里最快的,因为 Substring 总是最终从原始输入的单个块创建一个字符串,而 Remove< /code> 必须至少可能将起始块和结束块粘合在一起。

The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".

The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable.

(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.)

I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.

彩虹直至黑白 2024-09-17 01:29:21

我知道这是高度优化的领域,但这似乎是启动 BenchmarkDotNet 的一个很好的借口。此测试的结果(甚至在 .NET Core 上)是 SubstringRemove 稍快一些,在此示例测试中:19.37ns vs 22.52ns >删除。所以大约快了 16%。

using System;
using BenchmarkDotNet.Attributes;

namespace BenchmarkFun
{
    public class StringSubstringVsRemove
    {
        public readonly string SampleString = " My name is Daffy Duck.";

        [Benchmark]
        public string StringSubstring() => SampleString.Substring(1);

        [Benchmark]
        public string StringRemove() => SampleString.Remove(0, 1);

        public void AssertTestIsValid()
        {
            string subsRes = StringSubstring();
            string remvRes = StringRemove();

            if (subsRes == null
                || subsRes.Length != SampleString.Length - 1
                || subsRes != remvRes) {
                throw new Exception("INVALID TEST!");
            }
        }
    }

    class Program
    {
        static void Main()
        {
            // let's make sure test results are really equal / valid
            new StringSubstringVsRemove().AssertTestIsValid();

            var summary = BenchmarkRunner.Run<StringSubstringVsRemove>();
        }
    }
}

结果:

BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.253 (1809/October2018Update/Redstone5)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview-010184
  [Host]     : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT

|          Method |     Mean |     Error |    StdDev |
|---------------- |---------:|----------:|----------:|
| StringSubstring | 19.37 ns | 0.3940 ns | 0.3493 ns |
|    StringRemove | 22.52 ns | 0.4062 ns | 0.3601 ns |

I know this is hyper-optimization land, but it seemed like a good excuse to kick the wheels of BenchmarkDotNet. The result of this test (on .NET Core even) is that Substring is ever so slightly faster than Remove, in this sample test: 19.37ns vs 22.52ns for Remove. So some ~16% faster.

using System;
using BenchmarkDotNet.Attributes;

namespace BenchmarkFun
{
    public class StringSubstringVsRemove
    {
        public readonly string SampleString = " My name is Daffy Duck.";

        [Benchmark]
        public string StringSubstring() => SampleString.Substring(1);

        [Benchmark]
        public string StringRemove() => SampleString.Remove(0, 1);

        public void AssertTestIsValid()
        {
            string subsRes = StringSubstring();
            string remvRes = StringRemove();

            if (subsRes == null
                || subsRes.Length != SampleString.Length - 1
                || subsRes != remvRes) {
                throw new Exception("INVALID TEST!");
            }
        }
    }

    class Program
    {
        static void Main()
        {
            // let's make sure test results are really equal / valid
            new StringSubstringVsRemove().AssertTestIsValid();

            var summary = BenchmarkRunner.Run<StringSubstringVsRemove>();
        }
    }
}

Results:

BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.253 (1809/October2018Update/Redstone5)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview-010184
  [Host]     : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT

|          Method |     Mean |     Error |    StdDev |
|---------------- |---------:|----------:|----------:|
| StringSubstring | 19.37 ns | 0.3940 ns | 0.3493 ns |
|    StringRemove | 22.52 ns | 0.4062 ns | 0.3601 ns |
三岁铭 2024-09-17 01:29:21

.Net Core 中这也有效:

data = data[1..];

In .Net Core also this works:

data = data[1..];
朕就是辣么酷 2024-09-17 01:29:21

我猜想 RemoveSubstring 会并列第一,因为它们都占用字符串的固定大小部分,而 TrimStart > 从左侧进行扫描,对每个字符进行测试,然后必须执行与其他两种方法完全相同的工作。但说实话,这实在是令人毛骨悚然。

I'd guess that Remove and Substring would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.

李白 2024-09-17 01:29:21

如果你真的关心的话,你可以分析它。编写一个多次迭代的循环,看看会发生什么。然而,这很可能不是应用程序的瓶颈,而且 TrimStart 似乎在语义上是最正确的。在优化之前努力编写可读的代码。

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文