使用 Span<T> 可以显著提高性能。例如:
public static class StringExtensions
{
public static string ShiftString(this string s)
{
return string.Concat(s.AsSpan(1), s.AsSpan(0, 1));
}
}
基准测试
使用span标签,字符串的移动既更快速,也会产生较少的垃圾。同时保留html标签。
| Method | Data | Mean | Median | Allocated |
|
| L33t | ABCDEFGH | 18.56 ns | 18.21 ns | 40 B |
| Zs2020 | ABCDEFGH | 36.04 ns | 35.20 ns | 96 B |
| JohnWoo | ABCDEFGH | 47.69 ns | 47.39 ns | 104 B |
| AlinaB | ABCDEFGH | 52.56 ns | 52.07 ns | 104 B |
完整的测试代码
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Diagnostics.Windows;
using BenchmarkDotNet.Running;
namespace ConsoleApp10
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringShiftTest>();
}
}
[Config(typeof(Config))]
public class StringShiftTest
{
private class Config : ManualConfig
{
public Config() => AddDiagnoser(MemoryDiagnoser.Default, new EtwProfiler());
}
[Params("ABCDEFGH")]
public string Data;
[Benchmark]
public string L33t() => string.Concat(Data.AsSpan(1), Data.AsSpan(0, 1));
[Benchmark]
public string Zs2020() => (Data + Data).Substring(1, Data.Length);
[Benchmark]
public string JohnWoo() => Data.Substring(1, Data.Length - 1) + Data.Substring(0, 1);
[Benchmark]
public string AlinaB() => Data.Remove(0, 1) + Data.Substring(0, 1);
}
}