In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the method for C # to improve the operational performance of StringBuilder". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
In .NET, String objects are immutable. Each time you use one of the methods in the System.String class, a new string object is created in memory, which requires new space for that new object.
In cases where repeated modifications to a string are required, the overhead associated with creating a new String object can be very expensive. If you want to modify the string without creating a new object, you can use the System.Text.StringBuilder class. For example, using the StringBuilder class can improve performance when concatenating many strings together in a loop.
BenchmarkDotNet is a powerful .NET performance benchmark library that provides an isolated environment for each method being tested. With BenchmarkDotnet, programmers can easily write various performance testing methods and avoid many common pitfalls.
In this article, we will benchmark our StringBuilder operations using BenchmarkDotNet.
To use the code examples provided in this article, you should have Visual Studio 2019 or above installed on your system.
1. Create a console application project in Visual Studio
First, let's create a .NET Core console application project in Visual Studio. Assuming that Visual Studio 2019 is already installed on your system, follow these steps to create a new .NET Core console application project.
1. Start Visual Studio IDE.
two。 Click "create New Project".
3. In the create New Project window, select console Application (.NET Core) from the list of templates that appear.
4. Click "next".
5. In the "configure your New Project" window that appears next, specify the name and location of the new project.
6. Click create.
This will create a new .NET Core console application project in Visual Studio 2019. We will use this project to deal with StringBuilder in later chapters of this article.
two。 Install the BenchmarkDotNet NuGet package
To use BenchmarkDotNet, you must install the BenchmarkDotNet package. You can do this through the NuGet package manager within Visual Studio 2019 IDE, or by executing the following command in the NuGet package manager console.
Install-Package BenchmarkDotNet
3. Use StringBuilderCache to reduce allocation
StringBuilderCache is an inner class that is available in .NET and .NET Core. Whenever you need to create multiple instances of StringBuilder, you can use StringBuilderCache to greatly reduce the cost of allocation.
StringBuilderCache works by caching an StringBuilder instance and then reusing it when a new StringBuilder instance is needed. This reduces allocation because you only need to have one StringBuilder instance in memory.
Let's use some code to illustrate this. Create a class named StringBuilderBenchmarkDemo in the Program.cs file. Create a method called AppendStringUsingStringBuilder with the following code.
Public string AppendStringUsingStringBuilder () {var stringBuilder = new StringBuilder (); stringBuilder.Append ("First String"); stringBuilder.Append ("Second String"); stringBuilder.Append ("Third String"); return stringBuilder.ToString ();}
The code snippet above shows how to use the StringBuilder object to append a string. Next, create a method called AppendStringUsingStringBuilderCache, with the following code.
Public string AppendStringUsingStringBuilderCache () {var stringBuilder = StringBuilderCache.Acquire (); stringBuilder.Append ("First String"); stringBuilder.Append ("Second String"); stringBuilder.Append ("Third String"); return StringBuilderCache.GetStringAndRelease (stringBuilder);}
The above code snippet shows how to create an instance of StringBuilder using the Acquire method of the StringBuilderCache class, and then use it to append a string.
The following is the complete source code of the StringBuilderBenchmarkDemo class for your reference.
[MemoryDiagnoser] public class StringBuilderBenchmarkDemo {[Benchmark] public string AppendStringUsingStringBuilder () {var stringBuilder = new StringBuilder (); stringBuilder.Append ("First String"); stringBuilder.Append ("Second String"); stringBuilder.Append ("Third String"); return stringBuilder.ToString ();} [Benchmark] public string AppendStringUsingStringBuilderCache () {var stringBuilder = StringBuilderCache.Acquire () StringBuilder.Append ("First String"); stringBuilder.Append ("Second String"); stringBuilder.Append ("Third String"); return StringBuilderCache.GetStringAndRelease (stringBuilder);}}
You must now use the BenchmarkRunner class to specify the initial starting point. This is a way to tell BenchmarkDotNet to run the benchmark on the specified class.
Replace the default source code for the Main method with the following code.
Static void Main (string] args) {var summary = BenchmarkRunner.Run ();}
Now compile your project in Release mode and run the benchmark on the command line using the following command.
Dotnet run-p StringBuilderPerfDemo.csproj-c Release
The performance differences between the two methods are described below.
As you can see, using StringBuilderCache to append strings is much faster and requires less allocation.
4. Use StringBuilder.AppendJoin instead of String.Join
The String object is immutable, so modifying a String object requires the creation of a new String object. Therefore, when concatenating strings, you should use the StringBuilder.AppendJoin method instead of String.Join to reduce allocation and improve performance.
The following code list shows how to use the String.Join and StringBuilder.AppendJoin methods to assemble a long string.
[Benchmark] public string UsingStringJoin () {var list = new List
< string >{"A", "B", "C", "D", "E"}; var stringBuilder = new StringBuilder (); for (int I = 0; I)
< 10000; i++) { stringBuilder.Append(string.Join(' ', list)); } return stringBuilder.ToString();}[Benchmark]public string UsingAppendJoin() { var list = new List < string >{"A", "B", "C", "D", "E"}; var stringBuilder = new StringBuilder (); for (int I = 0; I < 10000; iTunes +) {stringBuilder.AppendJoin ('', list) } return stringBuilder.ToString ();}
The following figure shows the benchmark results of these two methods.
Note that the two methods are very close to each other for this operation, but StringBuilder.AppendJoin uses significantly less memory.
5. Append a single character using StringBuilder
Note that when using StringBuilder, if you need to append a single character, you should use Append (char) instead of Append (String).
Please consider the following two methods.
[Benchmark] public string AppendStringUsingString () {var stringBuilder = new StringBuilder (); for (int I = 0; I < 1000; iTunes +) {stringBuilder.Append ("a"); stringBuilder.Append ("b"); stringBuilder.Append ("c");} return stringBuilder.ToString ();} [Benchmark] public string AppendStringUsingChar () {var stringBuilder = new StringBuilder (); for (int I = 0) I < 1000; iTunes +) {stringBuilder.Append ('a'); stringBuilder.Append ('b'); stringBuilder.Append ('c');} return stringBuilder.ToString ();}
As you can see from the name, the AppendStringUsingString method shows how to append a string using a string as a parameter to the Append method.
The AppendStringUsingChar method shows how you use characters to append characters in the Append method.
The following figure shows the benchmark results of these two methods.
6. Other StringBuilder optimization methods
StringBuilder allows you to set capacity to improve performance. If you know the size of the string you want to create, you can set the initial capacity accordingly to greatly reduce memory allocation.
You can also improve StringBuilder performance by using a reusable pool of StringBuilder objects to avoid allocation.
Finally, please note that because StringBuilderCache is an internal class, you need to paste the source code into your project to use it. Recall that in C # you can only use one inner class in the same assembly or library.
Therefore, our program files cannot access the StringBuilderCache class simply by referencing the library where StringBuilderCache resides.
This is why we copied the source code of the StringBuilderCache class into our program file, the Program.cs file.
This is the end of the content of "what is the method of optimizing C # to improve the performance of StringBuilder operations". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.