Every time you add an item to a regular List, it re-allocates a new array. This is terrible for performance and garbage collection. Same thing happens when you remove items.
Unity hasn't updated their version of mono in many years, so yes, it's still true.
Hi there!
I was very surprised when I have seen BetterList class. And I was wondering, why System.Collections.Generic.List is so bad, and came there to find answer.
I've performed simple test in Unity Editor (Unity 4.3.4, Unity 3.5 .net full Base Class Libraries), that has shown, as I expected, that System.Collections.Generic.List works well, as expected, with memory.
Please see my
example code below:
using System.Collections.Generic;
var list = new List<int>();
Debug.Log("Initial capacity: " + list.Capacity);
for (int i = 0; i < 10; ++i)
{
list.Add(i);
Debug.Log(string.Format("Added element '{0}'. Current capacity = {1}", i, list.Capacity));
}
list.Clear();
Debug.Log("List capacity after clear: " + list.Capacity);
// Filling list for second time
for (int i = 0; i < 10; ++i)
{
list.Add(i);
Debug.Log(string.Format("Added element '{0}'. Current capacity = {1}", i, list.Capacity));
}
list.Clear();
Debug.Log("List capacity after clear: " + list.Capacity);
And the result:Initial capacity: 0
Added element '0'. Current capacity = 4
Added element '1'. Current capacity = 4
Added element '2'. Current capacity = 4
Added element '3'. Current capacity = 4
Added element '4'. Current capacity = 8
Added element '5'. Current capacity = 8
Added element '6'. Current capacity = 8
Added element '7'. Current capacity = 8
Added element '8'. Current capacity = 16
Added element '9'. Current capacity = 16
List capacity after clear: 16
Added element '0'. Current capacity = 16
Added element '1'. Current capacity = 16
Added element '2'. Current capacity = 16
Added element '3'. Current capacity = 16
Added element '4'. Current capacity = 16
Added element '5'. Current capacity = 16
Added element '6'. Current capacity = 16
Added element '7'. Current capacity = 16
Added element '8'. Current capacity = 16
Added element '9'. Current capacity = 16
List capacity after clear: 16
So, as we can see, new array allocated only when we trying to add more elements than capacity allows. If you know beforehand how much elements you are going to have in a list, you can pass this number to List's constructor, and it will allocate in memory array with corresponsind size.
All what I'm trying to say, that now System.Collections.Generic.List is working in Unity just like MSDN
says (at least for .NET 3.5).