Site icon Dotnet Helpers

Performance comparison between FOREACH LOOP and FOREACH-OBJECT using PowerShell

If you’re familiar with any programming language then you’re probably also familiar with a ForEach loop. A ForEach loop is a simple language construct that enables you to iterate through a set of items in a collection or array. Whatever programming language it may be, the ForEach loops behave works in the same way.

What will ForEach & ForEach-Object do?

Difference between FOREACH LOOP AND FOREACH-OBJECT

The ForEach statement loads all of the items upfront into a collection before processing them one at a time. ForEach-Object expects the items to be streamed via the pipeline, thus lowering the memory requirements, but at the same time, taking a performance hit.

ForEach-Object is best used when sending data through the pipeline because it will continue streaming the objects to the next command in the pipeline, You cannot do the same thing with ForEach () {} because it will break the pipeline and throw error messages if you attempt to send that output to another command.

Speed comparison (Foreach vs. Foreach-Object)

Measure-Command measures how long a command or script takes to complete. This is particularly important for processing large amounts of data. In this post, we going to use Measure-Command to calculate the performance of Foreach and Foreach-Object.

$items = 1…90000
Write-Host “Execution time taken for ForEach-Object =” (Measure-Command { $items | ForEach-Object { “Item: $_” }}).totalmilliseconds
Write-Host “Execution time taken for Foreach =” (Measure-Command { Foreach ($item in $items) { “Item: $element” }}).totalmilliseconds

Notice in the above case you don’t use $_ for ForEach and variable was explicitly declared ($item in this example). Note that two aliases exist for ForEach-Object; ForEach and %.

After the above execution, we can see the iteration time take for ForEach is less than ForEach-Object Cmdlet. Foreach consumes more memory (all objects are stored in memory) than ForEach but it’s faster. The Foreach-Object objects are processed one after another and the results for each object, which goes through the pipe are output instantly. But anyway, my favorite is Foreach-Object. 😉

Exit mobile version