Better PoSH: Avoid Using += for Arrays

I’ve found myself hanging around some PowerShell chats lately, and I’ve been picking up on a lot of neat tricks to write better code. This one comes my way via Adam Cook from his blog post on his awesome new function Get-CMUnusedSources (seriously, if you’re a ConfigMgr shop, check it out).

Since PowerShell is one of those languages we learn as we read other’s code and hack things together (at least to start), it’s easy to pick up on ways of doing things that are quick, but might not be the best idea in terms of performance. Most of the time it’s insignificant as it’ll barely matter on smaller scripts, but it’s always a good idea in this bloggers opinion to get into good habits for when you do start writing larger and more complex scripts.

Let’s start with a script that takes a folder, collects the files, and then adds each file to a list.

What’s happening here after I collect the files with Get-ChildItem is that I’m then looping over the results to update the array. It may seem like I’m just updating the same array over and over again, but what’s really happening is that I’m making a copy of the array and adding one item. Then I do this for every single file in $windowsFiles, which takes a very long time. In fact, we can prove that our array isn’t dynamic (and so cannot be directly updated) by trying to add a new item to it:

Instead, as Andy Svints explains in his blog post, we should use an ArrayList when possible. Here is the same snippet above written

The performance impact is amazing. While constantly recreating the static array took over 2,700ms to add about 9,500 items, the dynamic ArrayList took just 14ms.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.