String. Format or StringBuilder efficiency?

Source: Internet
Author: User

I suddenly remembered this. I could have written a blog...

The following is a question about the efficiency of String. Format or StringBuilder? As for this question,

Directly ask him to use the powerful weapon Reflector to learn about the String. Format method.

As a result, he quickly found out the relevant code:

Code

 public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}


Of course, it's too late, and I don't even have to post too much code to prove the difference between them.

Obviously, String. Format calls the StringBuilder class, but this does not indicate that String. Format is faster than StringBuilder, or that StringBuilder is faster than String. Format,

It can only be said that the StringBuild efficiency is determined by some factors, including the number of series and the size of strings,

But at least in the small number of codes we usually use, the difference can be ignored. For the current development application, there is no need to decide whether to win or lose. Let's look at the application scenarios ).

PS: StringBuilder first creates a buffer area when creating a string. When the StringBuilder operation changes the string data value,

StringBuilder checks whether the buffer size is sufficient to accommodate new string data. If not, the buffer size will increase the pre-determined quantity.

Because the memory configuration operation is greatly reduced, the efficiency can be effectively improved. I don't want to spend too much time on this topic...

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.