Options to Clear a StringBuilder
It turns out there are two common ways to clear a StringBuilder:Option #1: Create a new StringBuilder object
1
| StringBuilder sb = new StringBuilder(); |
sb.Length = 0; |
Which Option is Better?
Setting the Length property to zero is about 25% faster than creating a new StringBuilder object every time.Option 2 seems intuitively better because it does not create a new object on the heap every time. Even so, it’s not likely to make a noticeable performance difference in your software. When looping a million times on a fast PC, setting the Length to zero is about 1 second faster than creating a new object.
Sample Console Program
Here is a simple console program that demonstrates this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| using System; using System.Text; namespace CSharp411 { class Program { static void Main( string [] args ) { int loops = 1000000; int maxLength = 100; DateTime time1 = DateTime.Now; for ( int i = 0; i < loops; i++) { StringBuilder sb = new StringBuilder(); for ( int j = 0; j < maxLength; j++) { sb.Append( 'a' ); } } DateTime time2 = DateTime.Now; StringBuilder sb2 = new StringBuilder(); for ( int i = 0; i < loops; i++) { sb2.Length = 0; for ( int j = 0; j < maxLength; j++) { sb2.Append( 'a' ); } } DateTime time3 = DateTime.Now; Console.WriteLine( "new = {0}, append = {1}" , time2.Subtract( time1 ), time3.Subtract( time2 ) ); Console.ReadLine(); } } } |
new = 00:00:04.1050000, append = 00:00:03.0690000
No comments:
Post a Comment