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.