Skip to content

ForEach-Object operation statements are unexpectedly slower than script blocks; both are much slower than filter functions #7700

@mklement0

Description

@mklement0

Steps to reproduce

Update: Added a filter function.

Compare the performance of extracting the .Name property values from 1 million objects:

# PSv3+ operation statement (using parameters directly rather than a script block)
(Measure-Command { , (Get-Item /) * 1e6 | ForEach-Object Name }).TotalSeconds
# Script block
(Measure-Command { , (Get-Item /) * 1e6 | ForEach-Object { $_.Name } }).TotalSeconds
# Filter function
filter Name { $_.Name }
(Measure-Command { , (Get-Item /) * 1e6 | Name }).TotalSeconds

Note: (, (Get-Item /) * 1e6).Name - i.e., member enumeration - is the fastest by far, but this issue is about comparing streaming approaches.

Expected behavior

At the very least comparable performance.

Presumably, not having to evaluate a script block in each iteration has the potential to be faster.

I would expect a filter function to perform similarly to the script-block solution.

Actual behavior

The operation statement is noticeably slower than the script block.

Sample timings (averaged across 10 runs) on Windows, macOs, Ubuntu show varying ratios, ranging from the operation statement taking 1.24 as long to 1.58 to 1.85, respectively.

The factor for Windows PowerShell was 1.40.

The filter function is by far the fastest, by a factor of about 10 on macOS.

Environment data

PowerShell Core v6.1.0-rc.1 on macOS 10.13.6
PowerShell Core v6.1.0-rc.1 on Ubuntu 16.04.5 LTS
PowerShell Core v6.1.0-rc.1 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.165)
Windows PowerShell v5.1.17134.165 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.165)

Metadata

Metadata

Assignees

Labels

Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreWG-Cmdlets-Corecmdlets in the Microsoft.PowerShell.Core moduleWG-Engine-Performancecore PowerShell engine, interpreter, and runtime performance

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions