r/PowerShell • • 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/
128 Upvotes

23 comments sorted by

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

4

u/ISeeTheFnords Jul 18 '17

Yeah, it's hard to say what Microsoft was thinking by completely rebuilding the array when you add an object. I guess the language semantics make it necessary (unlike, say, Java where you can retain a reference to an object while changing it later), but it's still a pain.

0

u/[deleted] Jul 18 '17

[deleted]

2

u/bozho Jul 18 '17

Arrays are not immutable in .NET - they just cannot be resized. You can do this, for example:

$array = @(1, 2, 3)
$array[0] = 5

You are still operating on the same instance, altering its content (i.e. "state" in OOP parlance)

But, strings are immutable (you cannot change their state), so you can't do this:

$s = "foo"
$s[0] = [char]'F'

The advantage of arrays (over lists) is item access speed, but I don't know at which scale that becomes relevant in PowerShell...

1

u/Snak3d0c Jul 19 '17

It might be just me but the .NET makes everything so much less obvious and readable. Let alone that i would know that there is this option in .NET (which i don't).

Sure its faster and sure for big stuff that speed-factor might be important. But if i see the example in the OP blogpost about writing stuff to a file via .NET and you compare that with just out-file -append, well ... . If we are going to use .NET components all the time, why not just go for C# or something like that?

I'm not correcting btw, i'm just asking.

1

u/[deleted] Jul 19 '17

You've struck on a concept known as premature optimization. You are absolutely correct that higher level code is easier to understand and perfectly suitable in most cases. The OP article is specifically regarding cases where it is not suitable, at which point optimization becomes a necessity. The examples are merely that, examples; they aren't real world use cases.

Sure its faster and sure for big stuff that speed-factor might be important.

That's a bingo.

1

u/Snak3d0c Jul 19 '17

fair enough. Didn't know that term. TIL

1

u/ISeeTheFnords Jul 18 '17

Some implementations (Java's Vector, for instance) manage to combine the best of both worlds. I'd be much happier if PowerShell ALLOWED me to set the size of an array to avoid this. Failure to do so gives the WORST of both worlds.

1

u/bozho Jul 18 '17

Lists (.NET) and vectors (Java, STL in C++) are usually implemented with an array as an underlying storage. The array is only reallocated when more storage space is needed, using a strategy.

.NET's List<T>, for example reallocates twice the current size when needed, starting with a default size of 4 (you can check out the source code here)

For a reduced memory pressure, some list implementations may choose to grow half the current size (so x1.5 instead of x2)

Also, if you have a general idea about the size of your collection, you can construct a list with a pre-allocated storage to avoid reallocations:

$t = New-Object "System.Collections.Generic.List[int]" 42
$t.Capacity

2

u/ihaxr Jul 18 '17

Yep, another alternative is to use .NET lists which are very fast:

$intList = New-Object System.Collections.Generic.List[int]
1..10000 | % { $intList.Add($_) }

$objList = New-Object System.Collections.Generic.List[object]
Get-ChildItem | % { $objList.Add($_) }

$intList.Count
$objList.Count

$intList.Where({ $_ % 1000 -eq 0})

1

u/Eijiken Jul 18 '17

Going deeper on this, as I am foreign to how .net arrays work:

Let's say I do something like this...

$Files = Get-childitem $Path | where {$_.LastWriteTime -le [DateTime]::Today.AddDays(-30) -and $_.name -like "*.log"}

Would the correct way to add that to a .net array be:

$ObjList =  New-Object System.Collections.Generic.List[object]
$Files | % {$ObjList.Add($_)}

And how would you reference or call on that later on, like to say export the files to a csv or something of the sort?

1

u/ihaxr Jul 18 '17
$Files = Get-childitem $Path | where {$_.LastWriteTime -le [DateTime]::Today.AddDays(-30) -and $_.name -like "*.log"}

Already creates an array, so it's not entirely necessary to use a list.... so there are ways to avoid even having to use a list, but sometimes you want to be able to easily add or remove additional items... so you could do this:

$ObjList =  New-Object System.Collections.Generic.List[object]
Get-childitem $Path | where {$_.LastWriteTime -le [DateTime]::Today.AddDays(-30) -and $_.name -like "*.log"} | ForEach { $objList.add($_) }
Get-ChildItem $SomeOtherPath | ForEach { $ObjList.Add($_) }
$ObjList | Export-CSV -NoType "C:\temp\output.csv"

1

u/Eijiken Jul 18 '17

Awesome, just wanted to at least make sure the syntax was right. Thanks! That just helped immensely for when I get to that part in some code i'm working on.

1

u/AudaxDreik Jul 18 '17

That was my big revelation and takeaway from this too. I've got some code to clean up now.

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.4725

New-Object takes 15 seconds and the .net way takes less than one!

1

u/[deleted] Jul 19 '17

or use Classes

class Class{
[int]$Number
}

Measure-Command { 1..99999 | % {[Class]$Object = @{Number = $_}}}

2

u/nagasy Jul 18 '17

It seems I also did the array appending wrong. Thanks!

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

u/suddenarborealstop Jul 19 '17

The fastest code of all is code that never runs

1

u/nme_ Jul 18 '17

Will have to read this later!

I've had issues which office 365 on boarding speeds

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 -

  1. Don't hold anything in memory unless you absolutely have to

  2. Use methods and .Net as much as possible

  3. 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