ASP. NET (C #) string, stringbuilder and stringwriter Performance Comparison

Source: Internet
Author: User

Intuitive understanding: Confrontation
Performance Test 1: stringbuilder
1st tests: 312.5 milliseconds
2nd tests: 421.875 milliseconds
3rd tests: 453.125 milliseconds
4th tests: 421.875 milliseconds
5th tests: 453.125 milliseconds
Performance Test 2: stringwriter
1st tests: 406.25 milliseconds
2nd tests: 453.125 milliseconds
3rd tests: 421.875 milliseconds
4th tests: 437.5 milliseconds
5th tests: 437.5 milliseconds
Performance Test 3: string (1/100 data size)
1st tests: 12406.25 milliseconds

Have you noticed this?
In the test with only 1/100 data, the string connection time is 30 times that of stringbuilder. Therefore, we do not recommend this method based on performance considerations. Stringbuilder is slightly better than stringwriter. The specific cause will be analyzed below. Of course, there is an error in the test, but it is sufficient to explain the facts.

Stringwriter and stringbuilder: who is strong?
Stringwriter is located in the system. Io namespace and inherits from textwriter. The Decompilation result of. Net reflector shows that it is actually connected using stringbuilder internally. It is no wonder that stringwriter is slightly inferior. It was originally just an adaptation of stringbuilder (which can be called the adapter mode ). Why is stringbuilder so efficient?

Have you noticed this?
In many cases, stringwriter is required instead of stringbuilder, such as xmltextwriter.

Stringbuilder: Why?
There have been a lot of research on system. Text. stringbuilder on the Internet. The main principle is to allocate memory in an unmanaged way in advance to ensure text modification and expansion, and do not recreate a String object. The creation of string objects is the bottleneck of performance. Its connection efficiency is much higher than that of string, but it is easier to program string in a small amount of text connections.

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.