Fast String Operations

by Mar 18, 2016

String concatenation is a frequent thing in scripts but when you use the "+=" operator to append text to a string, this slows down your script considerably. A much better approach is to use a StringBuilder object to manipulate the string content.

Here are two examples, illustrating the tremendous performance differences:

# SLOW
$log = ''
Measure-Command {
  for ($x = 1 $x -lt 10000 $x += 1) 
  {
    $log += "I’ve just logged step $x"
  }
}


# FAST
$log = [System.Text.StringBuilder]''

Measure-Command {
  for ($x = 1 $x -lt 10000 $x += 1) 
  {
    $log.AppendLine("I’ve just logged step $x")
  }
}
$log.ToString()

Twitter This Tip! ReTweet this Tip!