Speeding Up Scripts with StringBuilder

by Jul 3, 2014

Often, scripts add new text to existing text. Here is a piece of code that may look familiar to you:

Measure-Command {
  $text = "Hello"
  for ($x=0 $x -lt 100000 $x++)
  {
    $text += "status $x"
  }
  $text 
}

This code is particularly slow because whenever you add text to a string, the complete string needs to be recreated. There is, however, a specialized object called StringBuilder. It can do the very same, but at lightning speed:

Measure-Command {
  $sb = New-Object -TypeName System.Text.StringBuilder
  $null = $sb.Append("Hello")
  
  for ($x=0 $x -lt 100000 $x++)
  {
    $null = $sb.Append("status $x")
  }
  
  $sb.ToString() 
}

Twitter This Tip! ReTweet this Tip!