Friday, March 2, 2012

Limit your use of the pipe

There have been many posts about the proper utilization of the powerful pipe. Filtering left to avoid piping to the Where-Object is always a good idea. Following is another example that demonstrates that judicious use of the pipe is a best practice.
We are going to define 3 scriptblocks that simply count to 100,000 and measure the time it takes them to run.
$limit = 100000         
$test1 = { foreach ($num in 1..$limit ) {$num} }
$test2 = { for($x=1; $x -le $limit; $x++) {$x} }
$test3 = { 1..$limit | foreach{$_} }

"ForEach: {0} seconds" -f (Measure-Command $test1).TotalSeconds
"For: {0} seconds" -f (Measure-Command $test2).TotalSeconds
"Pipe: {0} seconds" -f (Measure-Command $test3).TotalSeconds
On my machine these were the results:
ForEach: 0.0348825 seconds
For: 0.2490948 seconds
Pipe: 6.7627934 seconds

Enjoy!