小编Ric*_*rdo的帖子

在 C# 中使用 span 替换小字符串中出现的最快方法

我正在尝试最大限度地提高 C# 中 string.Replace 方法的 CPU 性能和内存优化。目标是减少内存分配和 CPU 时间,因为该项目位于 10000 rps 的 ASP.NET Core 中。

我发现了两个提高性能的技巧:1)使用Span Struct 2)使用String.Create

   internal struct ContextData
    {
        public string Origin { get; set; }
        public string Replace { get; set; }
        public string With { get; set; }
    }




    internal string SpanReplaceWithCreate(ContextData context)
    {
        int count = 0;
     
        ReadOnlySpan<char> origin_span = context.Origin.AsSpan();
        ReadOnlySpan<char> replace_span = context.Replace.AsSpan();
        ReadOnlySpan<char> replace_with = context.With.AsSpan();

        int index;
        ReadOnlySpan<char> tmp = origin_span;

        while ((index = tmp.IndexOf(replace_span)) > 0)
        {
            count++;
            tmp …
Run Code Online (Sandbox Code Playgroud)

c# performance .net-core asp.net-core

6
推荐指数
1
解决办法
7205
查看次数

标签 统计

.net-core ×1

asp.net-core ×1

c# ×1

performance ×1