Any benefit to using an array vs a List?

As I go through these courses I occasionally notice certain things that go against what I’ve learned at work (I use C# daily at my job). Often it’s just a different way to get to the same result, and this instance definitely qualifies for that as well, but I’m an inquisitive person so I feel the need to ask: is there a specific reason that we are using arrays vs Lists?

My understanding is that they serve the same basic function, but in my opinion Lists are much easier to wrap your head around, especially once you start wanting to add things to/remove things from the array/List. I know arrays tend to be quicker when you’re trying to retrieve a specific element, whereas Lists are quicker adding and removing elements, so maybe that’s the only reason (since in this case we already have the lasers created so we don’t need to worry about adding/removing items programmatically) but I wanted to ask to see if there were any other Unity-specific pros/cons I should be aware of.

Lists are really just wrappers around arrays. It does come with some downsides which is only really evident when you have large lists. Objects over 85,000 bytes go to the Large Object Heap and that can have performance issues later on. It is, however, quite difficult to get a list to be that big because the list usually only holds a pointer to the actual class that holds the data. The same is true for arrays, though.

When you create a list it is initialised to have an underlying array with size 0. As soon as you add something, that array is reinitialised to a size of 4. When these 4 elements have been filled and you need to add more items, the array is reinitialised to a size of current capacity * 2 so it becomes 8, and so on. But arrays cannot just be reinitialised, so the underlying code needs to create a new copy of the array with the new size, copy the existing items into it, and then start using the new array.
When you specify a capacity for the list (which you can do in the constructor), this will be the starting capacity instead of the 4 mentioned above. If we set it to 3 for example, the array will go from 0 to 3 to 6 to 12, etc.
Arrays are more performant in this sense, but the overhead on small lists are negligible and lists are definitely easier to use. It’s also easy to just set the initial capacity to a value large enough for your data to never get to the reinitialise part. If I know I’m going to hold 20 items, I can set the capacity to 20 and it will never reinitialise, where the default will have to do it at 4 items, 8 items and 16 items and leave me with 12 unused elements, too.

2 Likes

Awesome! Thanks for the breakdown of how each works, especially the reinitializing of lists.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms