C # string Performance description)

Source: Internet
Author: User
Tags coding standards

Performance Considerations for strings in C # [1]

C # string Performance

 

Written by Dr Herbie [2]

Translated by Allen Lee

Reviewed by Teddy Tam & Allen Lee [3]

 

Introduction

You areCodeThe method for processing strings in may have a surprising impact on the performance. In this article, I need to consider two problems caused by the use of strings: the use of temporary string variables and string connection.

 

Background

Every project requires you to consider coding standards for it. Using fxcop is a good start. One of my favorite fxcop rules is "performance.

So I used fxcop to check my project and find a series of string problems. I must admit one thing: I often encounter problems related to the immutable string of C. When I see mystring. when toupper (), I often forget that it does not change the content of mystring but returns a whole new string (because the string in C # is immutable ).

I corrected the Code to remove the warning from fxcop, and then I found that the code was indeed faster than before. I decided to conduct the investigation, and eventually I would write the code for the tests above.

 

Using the code

The test code is very simple. One ConsoleProgramCall four test methods, where each method executes a string processing routine 1000 times (the execution time is long enough to see the performance difference ).

The four test methods are divided into two groups, each of which is two. The first group compares two methods, which are used for case-insensitive string comparison.

 

String comparison and temporary string Creation

The first test routine is a lame non-case sensitive string comparison. The code for the comparison routine is:

Static   Bool Badcompare ( String Stringa, String Stringb)
{
Return(Stringa. toupper () = stringb. toupper ());
}

For this code, fxcop provides the following suggestions:

"Stringcomparetest. badcompare (string, string): Boolean callstring. op_equality (string, string): Boolean after converting 'stack1', a local, to upper or lowercase. if possible, eliminate the string creation and call the overload of string. compare that performs a case-insensitive comparison."

This suggestion means that each call to toupper () creates a temporary string, which is created and managed by the garbage collector. This requires additional time and memory usage. The string. Compare method (relatively speaking) is more efficient.

The second test routine uses string. Compare:

Static   Bool Goodcompare ( String Stringa, String Stringb)
{
Return(String. Compare (stringa, stringb,True, System. Globalization. cultureinfo. currentculture) = 0 );
}

This method prevents redundant temporary strings from being created.

According to the nprof analysis results, goodcompare only takes 1.69% Of the total execution time of the Code, while badcompare takes 5.50% Of the total execution time.

Therefore, the string. Compare method is more than three times faster than the toupper method. If you compare many strings in your code (especially in loops), you can use string. Compare to greatly improve the performance of your code.

 

String concatenation inside a loop

Finally, the test routine assumes that the string connection is carried out in a loop.

The code for the "lame" test routine is as follows:

Static   String Badconcatenate ( String [] Items)
{
String Strret = String . Empty;

Foreach ( String Item In Items)
{
Strret + = item;
}

Return Strret;
}

When fxcop sees this code, it will be very angry and even useRedMark this broken rule! Fxcop said:

"Change stringcomparetest. badconcatenate (string []): string to use stringbuilder instead of string. Concat or + ="

The code for the "excellent" test routine is as follows:

Static   String Goodconcatenate ( String [] Items)
{
System. Text. stringbuilder builder = New System. Text. stringbuilder ();

Foreach ( String Item In Items)
{
Builder. append (item );
}

Return Builder. tostring ();
}

This code is almost used as the first example to demonstrate the usage of system. Text. stringbuilder. The problem with poor code is that too many temporary strings are created. Due to the immutable character string, the concatenation operator (+ =) uses the original two strings to create a new string, and then points the original string instance to this new string.

However, based on nprof to study code performance, we found that running badconcatenate only requires 5.67% Of the total execution time, while goodconcatenate is 22.09%. That is to say:

Using stringbuilder takes almost four times as long as a simple string connection!

Why?

This is partly due to the design of this test-the connection routine only connects ten short strings. Stringbuilder is a more complex class than a simple and immutable string class. Therefore, it is much more expensive to create a stringbuilder than to connect ten simple strings.

I repeated the tests for different numbers of string connections and found the following results:

Note: The value shown here is the percentage of execution time of the test routine to the total execution time (% ). Goodconcatenate is actually not much faster, but it is relatively faster than badconcatenate.

Therefore, stringbuilder usually only shows the real performance advantage when the number of strings you want to connect exceeds 600.

Of course, another reason for using stringbuilder is the memory allocation. Use clrprofiler to generate the following sequence diagram of memory usage when 100 simple strings are connected:

The area marked as "a" shows the effect of badconcatenate on memory allocation and release. The maximum allocated memory increases rapidly with a large amount of garbage collection (approximately 215 garbage collection times in this region ).

The goodconcatenate memory profile is displayed immediately after Area. The maximum increment of allocated memory is small and accompanied by a very small amount of garbage collection (approximately 60 garbage collection times in this region ).

So in some cases, using the stringbuilder class will not (make your code run) faster, but it is friendly to the garbage collector.

 

Conclusions

Use the string. Compare method to compare non-case sensitive strings. This is faster. The code is elegant and simple.

Use stringbuilder for better speed only when you perform more than 600 string connections in a loop. Note that the length of the string you are processing will also affect the final speed and the effect of the garbage collector, therefore, you should analyze the problem based on your actual code.

 

Points of interest

To my surprise, the methods for using the correct code string operations in the real world are still quite different (although we have compared and connected many strings in the current project ).

Fxcop performance rules are a good starting point for discovering potential low-performance code and can guide you through some simple corrections to improve code performance. Both of the issues discussed here are marked as "NON-BREAKING" by fxcop, which means that changes should not corrupt the code that relies on the changed code. I think that the changes made to improve performance are "NON-BREAKING" is a brainless idea.

 

Further Considerations by Allen Lee

The majority of. NET developers agreed to use stringbuilder to process string connections. But have you ever wondered whether the applicability of this empirical principle is as broad as you think? After reading this article, you may have realized that this is a moderate problem. The improvements brought about by using stringbuilder for small-scale string connections are not enough to cover the overhead caused by the complexity of stringbuilder. Only when the connection scale reaches the critical scale can the two compensate each other and reach a balance.

For actual code, a critical scale value that can be used may be necessary, especially for development on restricted systems. You may have an understanding of the factors that affect the critical size and doubt the number given by the author here. Maybe the design used for testing in this article is a little simple and may not convince more people, but you do know through this article that stringbuilder is not applicable in any situation. Because factors that affect critical scale are always subject to change, you cannot find a fixed critical scale value that applies to any situation. You should customize your code and make adjustments at any time (because changes always exist), as long as you really care about the performance impact. As a starting point, you can use the number mentioned in this article as a reference and fine-tune the specific situation until you are satisfied.

 

History

    • : The first draft of this article is completed.
    • : With the assistance of Teddy Tam, the translation of this article was completed three times.
    • : Confirm the final translation of this article and complete post-processing.

 

    • [1]Copyright Notice: This translation is for study purposes only. All content (including text, data, and charts) from the original article (click here to view the original article) is copyrighted by the original author. Part or whole of the content cannot be reproduced in any form without permission.
    • [2] about the author Dr Herbie: click here to view otherArticleAnd the author's introduction.
    • [3] thanks to Teddy Tam, he gave me a lot of support and help throughout the translation process of this article, and provided many professional comments on the translation of this article!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.