For some tasks in life, being precise is a necessity. But most of us get away with rounding, paraphrasing, and hitting in the general vicinity most of the time. Depending on your personality, you may be one who strives for perfection and strains on every miniscule gnat. Or you may be the guy or gal who looks to set the bar as low as possible. As in so low that you could trip over it and still clear it. While I like to kid myself and think I’m always detailed and never lazy…there are times to be both. As my great, great grandfather used to say, “as in life, so too in Powershell.” And like life, even in the land of PowerShell there are times where going with the path of least resistance is the way to do it. Resistance being the limit of your knowledge, what you know from memory, or smacking down some dirty code to get the job done quickly, warts and all. Conversely, there are times when your code hangs in the balance between LIFE AND DEATH and you must be as efficient as possible. Okay, maybe that’s a tiny bit extreme, but there are definitely times where you have limited resources or specific window of time to process your code. So let’s talk about when to use an Array vs ArrayList.

\\\Array Charles

I’ve talked about and used arrays in several of my previous posts. Most likely, you use arrays frequently as most of your tasks probably involve repeating X on multiples objects. There are multiple ways to skin a cat (what a horrible analogy, but alas I’ve used it anyway) and arrays are no different. To begin with, here’s an easy way to define an array:

$Array = @('thing1','thing2')
Once we have it stored in our variable $Array, we can easily add to it like so:
$Array += 'thing3'
If we check the contents of $Array, we now see 3 thingys:
Array vs ArrayList Script Example 1

So far so good. And this is generally how I do it all the time when I’m writing something quick and dirty. I don’t even think about it. Writing it this way for me is like riding a bike or building a super complex rocket ship; it’s just muscle memory.

Before we get too far along, let’s check a few things about our array.

Array vs ArrayList Script Example 2

As expected, this shows that it is indeed an Array. No fireworks or magic tricks here. Now let’s do one more check and use the IsFixedSize method to see if the size is fixed:

Array vs ArrayList Script Example 3

This says it’s true and has a fixed size. That means we can’t add to it or remove from it. But I do it all the time, right? Am I going crazy or did we not just add to it using +=???

Technically, yes. But when you do += with a fixed array, it actually deletes the previous object and creates a new one each time since it can’t add to it. Check out this link from MS for more on the subject. One of the documents I read even used a strong word like “destroy” to show that this process is violent and not for the faint of heart.

That’s great, but who gives a flip, Kip?

Well, when you are dealing with a small number of items in your array it may not be that noticeable. But when you’re working with thousands or tens of thousands of items this performance hit is more noticeable than Liam Neeson’s identical roles in his last 10 movies.

*Enter stage left, ze ArrayList*

\\\ArrayList, Checking it Twice

This is where ArrayList comes busting onto the scene making promises like your favorite politician…but it actually follows through with them. Ouch, nothing but love for all of the PowerShell scripting politicians out there. I’m sure you’re the exception to this!

Anyway, let’s look at an ArrayList and how it differs from our usual Array. First, let’s look at an easy way to define it:

[Collections.ArrayList]$ArrayList = @('thing1','thing2')

Secondly, let’s check the type with the GetType() method:

Array vs ArrayList Script Example 4

Sweet! It’s an ArrayList! But why does it matter? Well, let’s check if it’s fixed size or not.

Array vs ArrayList Script Example 5

Well give me an ice cream cone and call me Joe Biden! An array list isn’t fixed. What that means in practice is that we can add to it/remove from it without recreating a completely new array each time. You add to it by using the Add() method (and remove using the Remove() method):

Array vs ArrayList Script Example 6
style="display:block" data-ad-client="ca-pub-3397982927006466" data-ad-slot="6462285589" data-ad-format="auto" data-full-width-responsive="true">

\\\silencio

There are a few other key differences to note in the Array vs ArrayList debate. As you may have noticed, when you add to an array it returns the number in the index. Although there are several different ways to prevent this, you can easily silence the backtalk by adding >$null at the end:

[Collections.ArrayList]$ArrayList.Add('thing3') >$null
style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-3397982927006466" data-ad-slot="6946690681">

\\\Not My Type

Another major difference is an array list doesn’t have type safety, meaning it can store any data type. One of the most common situations this has presented a problem for me is when I get more than 1 item returned in a query and instead of adding each as its own object in the array, it stores it as an array in the array. I’m sure that explanation was sparkling clear, but to demonstrate this, let’s look at adding some objects to an array. I’ll add some of the folders/files from my FIFA 22 save directory:

Array vs ArrayList Script Example 7

So let’s say I only wanted to add files and folders with the word SETUP to an array. There are 2 files that contain the word Setup in the name. Before adding them to an Array or an ArrayList, let’s just count ’em and check 0 in the index:

Array vs ArrayList Script Example 8

If I add these to an array, everything is the same:

Array vs ArrayList Script Example 9

However, look at what happens in an ArrayList:

Array vs ArrayList Script Example 10

Notice that it kept the type of the object I added to the ArrayList. Instead of having 2 objects, I have 1 array that contains the 2 objects. So to get the first file info, I would have to do something like this:

Array vs ArrayList Script Example 11

Additionally, you can also see the difference by checking the type:

Array vs ArrayList Script Example 12

\\\Speed Racer GO!

So now that we know some of the key differences and a common way that ArrayLists can trip us up if you’re used to using Arrays, let’s talk efficiency. First, let’s build some data to test with. My WinSxS folder has 15k child items. For this example, let’s compare the speed of adding each name to an Array vs Arraylist using Measure-Command:

$Total = Get-ChildItem C:\Windows\WinSxS\
$Array = @()
"Array = $((Measure-Command { $Total | %{$Array += $_.Name}}).TotalMilliseconds) milliseconds"
[Collections.ArrayList]$ArrayList = @()
"ArrayList = $((Measure-Command { $Total | %{$ArrayList.Add($_.Name) >$null}}).TotalMilliseconds) milliseconds"
Array vs ArrayList Script Example 13

IT’S OVER 9000!!!

Jk, it was only a mere 66X faster in our test using an ArrayList vs an Array. Wowzers.

In conclusion, other than a few potential gotchas with data types, ArrayLists provide a noticeable improvement in processing time compared to Arrays. This can speed up your scripts somethin’ fierce if you’re working with large amounts of data. Let me know your thoughts below and when you use Array vs ArrayList in your own scripts.

OTHER POSTS YOU WANT TO READ

Spice Up HTML Emails with PowerShell – Part III

So far in this series we've fumbled our way around the kitchen and tried to wing it when sending HTML emails with PowerShell. It was clunky to say the least. We then went through our spice rack and built an HTML template, highlighting the nuances of each spicy element...

Spice up HTML Emails with PowerShell – Part II

In Part I of our scrumptious concoction we put our script into the oven to let it bake. But we forgot to add our secret sauce that's sure to leave our recipients drooling, which is clearly our goal. In this post we'll continue to spice up HTML emails with PowerShell...

Spice Up HTML Emails with PowerShell – Part I

I live in the South, specifically in God's country AKA TEXAS BABAY! There's plenty of amazing things about Texas and definitely some reasons to loathe being from Houston, but it's hard to knock our food. I mean, is there really even a debate between Whataburger vs...

Disable O365 Apps in License (PowerShell)

If it's free, it's better. This is basically my mantra for life and a really easy one to follow at that. You can apply it to all sorts of things: ice cream, candy, food. Okay, maybe just free food tastes better when you know you didn't have to pay for it. Especially...

Font Installer Script (PowerShell)

Things have smells. I know, this is a revolutionary idea and you may need to stop right here and take a breather while you process this massive revelation. Things that are brand new have a particular smell that vanishes shortly after hitting your nostrils. It's...
%d bloggers like this: