Is A + = B really different from A + B?

Source: Internet
Author: User

Today I saw an article about how to improve program performance in. NET, which contains the following:

We recommend that you use simplified operators such as + = and-=.
For example, the original expression A = A + B
Change to A + = B
This not only reduces the number of code hits, but also increases the system performance at runtime because variable A appears only once.

It is true that such operations can reduce input, but do not know whether the performance can be improved and how to improve the performance (whether the code is optimized or the space is saved, with curiosity, I tried it myself. First, I wrote two test methods:

       static void test1()   

{
string A = "string A";
string B = "string B";
A += B;
}

static void test2()
{
string A = "string A";
string B = "string B";
A = A + B;
}

After compilation, use ildasm to check the IL values of the two methods. We can see that the IL values of the two methods are the same:

 .maxstack  2   
.locals init ([0] string A,
[1] string B)
IL_0000: nop
IL_0001: ldstr "string A"
IL_0006: stloc.0
IL_0007: ldstr "string B"
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: call string [mscorlib]System.String::Concat(string,
string)
IL_0014: stloc.0
IL_0015: ret

Since IL is the same, the code after reflector decompilation must be the same.

Here we can view the optimization level respectively:

 // The optimization level is NONE.

Private static void test1 () // or test2
{
String;
String B;
A = "string ";
B = "string B ";
A = A + B;
Return;
} // The optimization level is. NET 3.5 private static void test1 () // or test2

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.