我知道这是一个超级优化的领域,但这似乎是一个很好的借口来踢BenchmarkDotNet的轮子。这个测试的结果(甚至在。net Core上)是Substring比Remove稍微快一点,在这个示例测试中:Remove为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>();
}
}
}