PowerShell

Measure-Command: A speed comparison (Foreach vs. Foreach-Object)

Measure-Command measures how long a command or script takes to complete. This is particulary important for processing large amounts of data.

Measure-Command

In this first example, I measure the command Get-ChildItem by searching all files with the file name Windows.

Measure-Command {Get-Childitem -Path c: -File -Recurse -ErrorAction SilentlyContinue | Where-Object Name -eq "Windows"}

1.PNG

It took about 44 seconds. That’s fast. I have a SSD.

The Comparison

Foreach-Object

Now, let’s measure another command with Foreach-Object:

Measure-Command {0..1000000 | Foreach-Object $_}

Unbenannt.JPG

8 seconds. Not bad.

Foreach

If I do the same with foreach instead of Foreach-Object then I have to accept, that I’m much faster.

$i=0
Measure-Command {foreach ($i in 0..1000000) {$i++}}

Unbenannt.JPG

3,5 seconds. Microsoft explains why it is as it is:

https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/08/getting-to-know-foreach-and-foreach-object/

Conclusion

Foreach consumes more memory, but it’s faster. All objects are stored in memory. With Foreach-Object the objects are processed one after another and the results for each object, which goes through the pipe is output instantly. Anyway, my favourite is Foreach-Object. 😉

More: https://www.pluralsight.com/blog/tutorials/measure-powershell-scripts-speed.

Categories: PowerShell

Tagged as: ,

2 replies »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.