PowerShell filter vs. function

Posted by Marcel Janus on Server Fault See other posts from Server Fault or by Marcel Janus
Published on 2013-11-09T06:38:04Z Indexed on 2013/11/09 9:58 UTC
Read the original article Hit count: 381

Filed under:

I'm reading currently the Windows PowerShell 3.0 Step by Step book to get some more insights to PowerShell.

On page 201 the author demonstrates that a filter is faster than the function with the same functionally.

This script takes 2.6 seconds on his computer:

MeasureaddOneFilter.ps1
Filter AddOne 
{  
  "add one filter" 
  $_ + 1 
}

and this one 4.6 seconds

MeasureaddOneFunction.ps1
Function AddOne 
{   
  "Add One Function" 
  While ($input.moveNext()) 
   { 
     $input.current + 1 
   } 
} 

If I run this code is get the exact opposite of his result:

.\MeasureAddOneFilter.ps1
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 226
Ticks             : 2266171
TotalDays         : 2,62288310185185E-06
TotalHours        : 6,29491944444444E-05
TotalMinutes      : 0,00377695166666667
TotalSeconds      : 0,2266171
TotalMilliseconds : 226,6171

.\MeasureAddOneFunction.ps1

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 93
Ticks             : 933649
TotalDays         : 1,08061226851852E-06
TotalHours        : 2,59346944444444E-05
TotalMinutes      : 0,00155608166666667
TotalSeconds      : 0,0933649
TotalMilliseconds : 93,3649

Can someone explain this to me?

© Server Fault or respective owner

Related posts about powershell