This is over a year old, but top of Google results. Originally I was doing this:
StringBuilder builder = new StringBuilder();
// Append to StringBuilder.
for (int i = 0; i < 10; i++)
{
builder.Append(i + " ");
}
Console.WriteLine(builder);
Then I thought that's probably defeating the point of using StringBuilder
. I started doing it like
StringBuilder builder = new StringBuilder();
// Append to StringBuilder.
for (int i = 0; i < 10; i++)
{
builder.Append(i);
builder.Append(" ");
}
Console.WriteLine(builder);
Finally, I realized I can chain methods to have it like @Habeeb. It got me wondering if there's any performance benefits.
$e1 = [Text.StringBuilder]::new()
$e2 = [Text.StringBuilder]::new()
function ef1(){
Write-Host "Start Date:" (Get-Date)
for($i=0;$i -lt 100000;$i++){
$e1.Append("Hello") | Out-Null
$e1.AppendLine($i.ToString()) | Out-Null
$e1.Append("World") | Out-Null
$e1.AppendLine($i.ToString()) | Out-Null
$e1.Append("More Lines") | Out-Null
$e1.AppendLine($i.ToString()) | Out-Null
}
}
function ef2(){
Write-Host "Start Date:" (Get-Date)
for($i=0;$i -lt 100000;$i++){
$e1.Append("Hello").AppendLine($i.ToString()).Append("World").AppendLine($i.ToString()).Append("More Lines").AppendLine($i.ToString()) | Out-Null
}
Write-Host "End Date:" (Get-Date)
}
This was a rough throw together, and I realize it's in PS. But, ef1
resulted in 17 seconds, and ef2
resulted in 3 seconds (not considering milliseconds here). Unless I'm mistaken, chaining methods is insanely performance improving. (And yes, this is possibly not unique to StringBuilder
, but StringBuilder
led me to ask this question.)
Update:
Thanks to @cogumel0, I realize now how expensive Out-Null
is. Increasing the iterations another digit shows ef1
takes about 4 seconds and ef2
about 1 second. (I also added the missing write end date for ef1
.)
$e1 = [Text.StringBuilder]::new()
$e2 = [Text.StringBuilder]::new()
function ef1(){
Write-Host "Start Date:" (Get-Date)
for($i=0;$i -lt 1000000;$i++){
[void] $e1.Append("Hello")
[void] $e1.AppendLine($i.ToString())
[void] $e1.Append("World")
[void] $e1.AppendLine($i.ToString())
[void] $e1.Append("More Lines")
[void] $e1.AppendLine($i.ToString())
}
Write-Host "Start Date:" (Get-Date)
}
function ef2(){
Write-Host "Start Date:" (Get-Date)
for($i=0;$i -lt 1000000;$i++){
[void] $e1.Append("Hello").AppendLine($i.ToString()).Append("World").AppendLine($i.ToString()).Append("More Lines").AppendLine($i.ToString())
}
Write-Host "End Date:" (Get-Date)
}