Automatic Unrolling and Memory Consumption

by Jan 30, 2015

PowerShell 3.0 and later

In PowerShell 3.0, a new feature called “Automatic Unrolling” was introduced. With it, you can write code like this:

(Get-ChildItem -Path $env:windir\system32 -Filter *.dll).VersionInfo  

This line takes all DLL files found in the System32 subfolder and for each file returns the VersionInfo property (essentially the DLL version). Prior to automatic unrolling, you had to write the loop yourself:

Get-ChildItem -Path $env:windir\system32 -Filter *.dll | ForEach-Object { $_.VersionInfo } 

When you run both examples, they yield exactly the same results. However, you will immediately discover the price you pay for automatic unrolling: it takes much longer until you see results. The first line may take as much as 10 seconds before you see results, whereas the “classic” approach returns information almost instantaneously.

The reason is not a difference in overall performance. Instead, automatic unrolling really produces code like this:

$data = Get-ChildItem -Path $env:windir\system32 -Filter *.dll
Foreach ($element in $data) { $element.VersionInfo } 

While automatic unrolling can be more intuitive and easier to code, writing loops yourself provides more compatible code and produces results faster.

Twitter This Tip! ReTweet this Tip!