Saya tahu ini adalah hiper-optimasi tanah, tetapi sepertinya alasan yang bagus untuk menendang roda BenchmarkDotNet
. Hasil tes ini (pada .NET Core) adalah yang Substring
sedikit lebih cepat daripada Remove
, dalam tes sampel ini: 19.37ns vs 22.52ns untuk Remove
. Jadi beberapa ~ 16% lebih cepat.
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>();
}
}
}
Hasil:
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 |
/
?