net8字符串匹配查找System.Buffers.SearchValues类
新增的 System.Buffers.SearchValues类,可以用来进行字符串的查找和匹配,相比较 string 类型的操作,性能有大幅提升,下面还是用 BenchmarkDotNet 进行测试:
BenchmarkRunner.Run<SearchValuesTest>(); Console.ReadKey(); [SimpleJob(RunStrategy.ColdStart, iterationCount: 5)] public class SearchValuesTest { [Benchmark] public void TestString() { var str = "!@#$%^&*()_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 100000000; i++) { str.Contains("z"); } } [Benchmark] public void TestSearchValues() { var sv = SearchValues.Create("!@#$%^&*()_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"u8); byte b = (byte)"z"[0]; for (int i = 0; i < 100000000; i++) { sv.Contains(b); } } }
从运行结果看,有大约 5 倍的的提升