How to use ObjectPool in C# to improve the performance of StringBuilder

In C#, we know that using StringBuilder can improve the efficiency of splicing a large number of strings. In fact, the efficiency of StringBuilder can also be improved, that is, using ObjectPool. The following describes how to use ObjectPool to improve the performance of StringBuilder.
1. Introduction       The C# ObjectPool class is a built-in class library for implementing the object pool pattern. It allows you to reduce the overhead of object creation and destruction by creating a predefined number of object instances in your application and making them available for reuse without having to create a new object each time. The ObjectPool class also provides control over the size of the object pool and the life cycle of the objects.
2. Use ObjectPool<StringBuilder> and performance test     First create a .NET7 console project, and then use the nuget package manager to install the ObjectPool package "Microsoft.Extensions.ObjectPool", or you can use the nuget code to install. Once the package is installed you can start using it. The steps to use the code are as follows:

1. Create the ObjectPool pool of StringBuilder:

private readonly ObjectPool<StringBuilder> _stringBuilderPool =    new DefaultObjectPoolProvider().CreateStringBuilderPool();

 2. Please use Get() to get the StringBuilder from the pool as shown below

var sb = this._stringBuilderPool.Get();

 3. Use it like StringBuilder to simulate connecting strings in the array

for (var index = 0; index < this._stringArray.Length; index++)
{   
 _ = sb.Append(this._stringArray[index]);
}

 4. When the StringBuilder is no longer needed, return it to the pool

_stringBuilderPool.Return(sb);

 5. Compared with the performance test using StringBuilder alone, first use a single instance to create an ObjectPool<StringBuilder>, then create a new string array of 300,000, and then use ObjectPool<StringBuilder> and StringBuilder to splice strings in a loop, and use Stopwatch during use Timing, the number of strings is gradually decreased to test, the code is as follows:

//引用ObjectPool
using Microsoft.Extensions.ObjectPool;
static void Main(string[] args)
 {
    #region
     //创建测试数组
     List<string> _stringArray=new List<string>();
     for (int i = 0; i <300000; i++)
      {
           _stringArray.Add("欢迎关注公众号:DOTNET开发跳槽"+i);
      }
      //创建Stopwatch 计时
    Stopwatch stopwatch = new Stopwatch();
     stopwatch.Start();
     //创建一个 ObjectPool<StringBuilder>
      ObjectPool<StringBuilder> _stringBuilderPool =new DefaultObjectPoolProvider().CreateStringBuilderPool();
     var sb = _stringBuilderPool.Get();
     for (var index = 0; index < _stringArray.Count; index++)
     {
         _ = sb.Append(_stringArray[index]);
     }
     _stringBuilderPool.Return(sb);
     stopwatch.Stop();
     // 获取TimeSpan值形式的运行时间。
     TimeSpan ts = stopwatch.Elapsed;
    Console.WriteLine($"使用ObjectPool的运行时间:{ts.Ticks}");
    //重新计时
     stopwatch.Restart();
     //使用StringBuilder实现
     StringBuilder sb2 = new StringBuilder();
     for (var index = 0; index < _stringArray.Count; index++)
     {
         _ = sb2.Append(_stringArray[index]);
     }
     stopwatch.Stop();
     TimeSpan ts2 = stopwatch.Elapsed;
     Console.WriteLine($"使用StringBuilder的运行时间:{ts2.Ticks}");
     #endregion
 }

 

 

It can be seen from the test data that the efficiency of ObjectPool<StringBuilder> is higher than that of StringBuilder when it is more than 50,000, and you can refer to it when using it. The specific efficiency depends on the configuration of the computer and the process of using the computer. It is not a professional test, and the above test is for reference only.

To sum up,
   the above describes how C# uses ObjectPool to improve the performance of StringBuilder, and uses a case to compare and test the use of StringBuilder and ObjectPool<StringBuilder>. According to the test results, it is not efficient to use ObjectPool<StringBuilder> in all cases. Also just as StringBuilder is not recommended when the amount of data is small. In addition, ObjectPool has more than this function. It can add other objects to help reduce the overhead of object creation and destruction, and improve the performance of the application.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130646630