A thorough understanding of the use of StringBuilder _c# tutorials

Source: Internet
Author: User

Today used to StringBuilder to stitching query statements, found this really useful, decided to make a summary.

Baidu is a StringBuilder definition: the String object is immutable. Each time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new space to be allocated for the new object. The system overhead associated with creating a new string object can be expensive when you need to perform repeated modifications to the string. If you want to modify a string without creating a new object, you can use the System.Text.StringBuilder class.

It is mainly the StringBuilder append () method and the Capacity property.

Note that when the capacity is less than length, the capacity is expanded in twice-fold way.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Use of namespace StringBuilder
{
  class program
  {
    static void Main (string[] args)
    {
      StringBuilder s = new StringBuilder ();
      Long Datastart = DateTime.Now.Ticks;
      for (int i = 0; i < 1000 i++)
      {
        s.append (' A ', i);
      }
      Long dataend = DateTime.Now.Ticks;
      Console.WriteLine (s.capacity);
      Console.WriteLine ("Spents: {0}", (Dataend-datastart)/100000.0);
      Datastart = DateTime.Now.Ticks;
      for (int i = 0; i < 1000 i++)
      {
        s.append (' A ', i);
        if (S.capacity < s.length)
        {
          s.capacity = 8;
        }
      }
      Dataend = DateTime.Now.Ticks;
      Console.WriteLine ("Spents: {0}", (Dataend-datastart)/100000.0);
      Console.read ();}}

Output results:

The above in-depth understanding of the use of StringBuilder is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.