Use the string type correctly in the. NET Program

Source: Internet
Author: User
Tags mscorlib

In actualProgramString type is widely used. However, improper use of. Net for string type variables seriously affects program performance. We will discuss this issue in several aspects:

1. Understand the memory allocation method of string data

Write a console application and enter the following testCode:

Class Program
{
Static void main (string [] ARGs)
{
String S = "";
S = "ABCD ";
}
}

Use the ildasm.exe tool of. NET Framework 2.0 sdk.exe to view the generated msil command:

01. Method private hidebysig static void main (string [] ARGs) cel managed
02 {
03. entrypoint
04 // code size 14 (0xe)
05. maxstack 1
06. Locals Init ([0] string S)
07 il_0000: NOP
08 il_0001: ldstr ""
09 il_0006: stloc.0
10 il_0007: ldstr "ABCD"
11 il_000c: stloc.0
12 il_000d: Ret
13} // end of method program: Main

Briefly explain the above msil command code:

Clause 06th assigns an index number to the local variable S (index number starts from 0. If the function contains multiple local variables, the index number is added in the order in the function ).

During compilation, the compiler writes the two strings "A" and "ABCD" in the Code to the Assembly metadata (metadata, these two strings are called "string literal )".

In the first sentence, use the ldstr command to allocate memory for the string object "a" and press the reference of this object into the thread stack.

The stloc command is used to pop up the referenced object from the top of the thread stack and pass it to the local variable S (its index number is 0 ).

The same process repeats "ABCD" once, so the two simple codes

String S = "";
S = "ABCD ";

The CLR will use the ldstr command to allocate the memory twice.

According to the above analysis, the reader must understand that the content of the string variable is read-only. Assigning different values to it will lead to memory reallocation. Therefore, to improve program performance, we should minimize the memory allocation during programming.

This section analyzes the common string usage in the Code, from which you can know how to avoid string operations that seriously affect program performance.

2. Use the string addition operator as few as possible

See the following two sections of code:

(1) string S1 = "AB ";
S1 + = "cd ";
(2) string S1 = "AB" + "cd ";

These two pieces of code run the same result, but the speed is the same as fast? See the msil command generated by the code in section (1:

 

. locals Init ([0] string S1)
il_0000: NOP
il_0001: ldstr "AB"
il_0006: stloc.0
il_0007: ldloc.0
il_0008: ldstr "cd"
il_000d: Call string [mscorlib] system. string: Concat (string,
string)
il_0012: stloc.0
il_0013: Ret

Let's look at the instructions generated by the code in section (2:

. Locals Init ([0] string S1)
Il_0000: NOP
Il_0001: ldstr "ABCD"
Il_0006: stloc.0
Il_0007: Ret

It can be clearly seen that the code segment (1) will cause the Concat () method of the string class to be called (implementing the string addition operation ). For section (2) Code, the C # compiler intelligently combines the two strings into a string literal during compilation, so when the program runs, the CLR only calls the ldstr command once to complete all the work. The execution speed is self-evident!

# P #

3. Avoid using addition operators to connect different types of data

See the following code:

String STR = "100 + 100 =" + 200;
Console. writeline (STR );

The generated msil command is:

 

. maxstack 2
. locals Init ([0] string Str)
il_0000: NOP
il_0001: ldstr "100 + 100 ="
il_0006: LDC. i4 0xc8
il_000b: Box [mscorlib] system. int32
il_0010: Call string [mscorlib] system. string: Concat (object,
Object)
il_0015: stloc.0
il_0016: ldloc.0
il_0017: Call void [mscorlib] system. console: writeline (string)
il_001c: NOP
il_001d: Ret

As you can see clearly, these two C # Codes not only cause the Concat () method of the string class to be called (il_0010), but also cause the boxing operation (il_000b )!

The Concat () method will cause CLR to allocate memory space for new strings. The boxing operation requires not only memory allocation, but also an anonymous object. After the object is created, there must be a data replication process, expensive!

Change to the following code:

String STR = "100 + 100 = ";
Console. Write (STR );
Console. writeline (200 );

The generated msil command is:

. Maxstack 1
. Locals Init ([0] string Str)
Il_0000: NOP
Il_0001: ldstr "100 + 100 ="
Il_0006: stloc.0
Il_0007: ldloc.0
Il_0008: Call void [mscorlib] system. Console: Write (string)
Il_000d: NOP
Il_000e: LDC. I4 0xc8
Il_0013: Call void [mscorlib] system. Console: writeline (int32)
Il_0018: NOP
Il_0019: Ret

We can see that although there is one more method call (console. write) method, but avoids complicated packing operations, and avoids calling string. the Concat () method frequently allocates memory for better performance.

4. Use stringbuilder instead of string to implement string connection in a loop

In some cases, multiple substrings need to be dynamically connected into a large string. For example, many complex SQL commands are generated through cyclic statements. In this case, do not use the addition operator of the string class. For example:

String STR = "";
For (INT I = 1; I <= 10; I ++)
{
STR + = I;
If (I <10)
STR + = "+ ";
}

The above code will generate a string: 1 + 2 +... + 10.

Refer tool to view the msil commands generated by the above Code.

Modify the following code to improve the program performance:

// Pre-allocate 1 kb of memory space
Stringbuilder sb = new stringbuilder (1024 );
For (INT I = 1; I <= 10; I ++)
{
SB. append (I );
If (I <10)
SB. append ("+ ");
}
String result = sb. tostring ();

By using the ildasm.exe tool to view the generated msil code, it is found that although the above Code generates seven more msil commands than the previous one, it avoids time-consuming packing operations, in addition, the memory allocation times are much less. When the number of loops is large, the running performance of the two code segments varies greatly.

Source link: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1441952

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.