r/PowerShell • u/rschiefer • Jul 18 '17
Slow Code: Top 5 Ways to Make Your PowerShell Scripts Run Faster
https://blogs.technet.microsoft.com/ashleymcglone/2017/07/12/slow-code-top-5-ways-to-make-your-powershell-scripts-run-faster/5
u/inamamthe Jul 18 '17
I'd also add to use asynchronous stuff when it makes sense to. I've found that particularly useful when having to perform the same operation multiple times on multiple remote servers. Invoke-Command has a handy -asJob switch which I tend to use a lot.
4
u/persistent13 Jul 18 '17
That was a great post, it covered some usefully tips! I'll be adding it to my bookmarks.
One topic that the post did not cover is object creation. The .net method introduced in PowerShell 5 is usually an order of magnitude faster than New-Object.
Consider the following where 99,999 objects are created:
New-Object
Measure-Command { 1..99999 | % { New-Object -TypeName System.Collections.Generic.List[object] } }
Days : 0
Hours : 0
Minutes : 0
Seconds : 15
Milliseconds : 658
Ticks : 156587400
TotalDays : 0.000181235416666667
TotalHours : 0.00434965
TotalMinutes : 0.260979
TotalSeconds : 15.65874
TotalMilliseconds : 15658.74
.net
Measure-Command { 1..99999 | % { [System.Collections.Generic.List[object]]::new() } }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 731
Ticks : 7314725
TotalDays : 8.46611689814815E-06
TotalHours : 0.000203186805555556
TotalMinutes : 0.0121912083333333
TotalSeconds : 0.7314725
TotalMilliseconds : 731.4725New-Object takes 15 seconds and the .net way takes less than one!
1
1
Jul 19 '17
or use Classes
class Class{ [int]$Number } Measure-Command { 1..99999 | % {[Class]$Object = @{Number = $_}}}
2
2
u/spyingwind Jul 18 '17
TL;DR: Unnecessary loops, and recreating arrays in those loops takes the most amount of time if dealing with massive amounts of data.
2
1
1
u/fourierswager Jul 19 '17
If only this blog existed a week ago...I had to solve a problem, I wrote a solution in PowerShell, but it was far too slow. I went to rewrite in C#, but it was time sensitive and I couldn't finish the C# in time...
In any case, these tips can be boiled down to the following -
Don't hold anything in memory unless you absolutely have to
Use methods and .Net as much as possible
Don't iterate over arrays if you can avoid it
Given my experience this past week, if I ever have any concerns about speed, I'm just going to use C# / .Net Core
9
u/Eijiken Jul 18 '17
Very good stuff! I didn't know how slow appending arrays were, and this is going to save me a bunch of time for sure!
Well timed post