Test Code below: This will test how much time it actually takes for the loops to complete.
$a=Get-ChildItem –File C:\users\dhrub\ -Recurse
$time = (Measure-Command {
$a | ForEach-Object {
$_
}
}).TotalMilliseconds
[pscustomobject]@{
Type = 'ForEach-Object'
Time_ms = $Time
}
$Time = (Measure-Command {
ForEach ($i in ($a)) {
$i
}
}).TotalMilliseconds
[pscustomobject]@{
Type = 'ForEach'
Time_ms = $Time
}
Output:
Type Time_ms
---- -------
ForEach-Object 213.3006
ForEach 64.8013
The Output will surely shock you !
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.
Forach will be always faster than Foreach-object but this doesn’t determine you don’t use foreach-object. It always depends upon the requirement of the work.