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 倍的的提升

 

posted @ 2024-01-29 10:00  ziff123  阅读(65)  评论(0编辑  收藏  举报