Similarities and differences between String and StringBuilder

Source: Internet
Author: User

Similarities:

Both objects are string operations,

Differences:

  String typeEach time the string is referenced, the space will be allocated again, and the originally allocated space will also exist. If you repeat the operation, it will occupy a large amount of memory space, thus wasting memory resources, such:

String str = "life ";

Str = str + "you ";

First, a str variable is defined to allocate physical memory space for the string "Lifetime,

The str value is now "you are in your life", and a physical space is also allocated in the memory to store "you have in your life", but the memory space allocated in the memory last time is "Lifetime ", it also occupies memory space.

  StringBuilder classWhen referenced by an instance, strings in its original physical memory are operated and no other physical space is allocated.

Physical space operations, so there will be no signs of resource waste. For example:

StringBuilder sb = new StringBuilder ("life ");
Sb. Append ("you ");
Response. Write (sb );

Performance Comparison Between string and StringBuilder

String str = "";
StringBuilder sbstr = new StringBuilder ();
Int times = 1000;
Int end = 0, start = 0;
// Time used to test the sting
For (int I = 0; I <times; I ++)
{
Str + = I. ToString ();
}
End = Environment. TickCount;
Console. WriteLine (end-start ));

// Time used to test stringbuilder
Start = Environment. TickCount;
For (int k = 0; k <times; k ++)
{
Sbstr. Append (k. ToString ());
}
End = Environment. TickCount;
Console. WriteLine (end-start );
Console. ReadKey ();

Running result: (milliseconds used)

Str: 416670062

Sbstr: 0

Through the above analysis, we can see that the connection validity rate of strings is very low, but not all cases use StringBuilder. When we connect a few strings, we can use String, however, StringBuilder must be used for a large number or frequent string connection operations.

 

Learning ....

 

 

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.