C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: The List collection is built up at runtime. It may have to allocate or change the positions in memory during garbage collection.
List AddNote: The int array is declared and created in one statement. Thus it will store all values in neighboring memory.
Int ArrayC# program that uses List
using System.Collections.Generic;
class Program
{
static void Main()
{
// Compare time to build up a List.
List<int> list = new List<int>();
for (int i = 0; i < 60000; i++)
{
list.Add(i);
}
}
}
C# program that uses array
using System.Collections.Generic;
class Program
{
static void Main()
{
// Compare time to allocate an array and assign to it.
int[] array = new int[60000];
for (int i = 0; i < 60000; i++)
{
array[i] = i;
}
}
}
Memory usage for arrays and Lists:
List generic: 6.172 MB
Integer array: 5.554 MB
Lookup performance for arrays and Lists:
List generic: 1043.4 ms
Integer array: 980.2 ms
And: Arrays were about 7% faster, even when other code is involved. The usage was with a data structure that looks up items.
Tip: These findings are only useful as a hint of how you can influence performance by changing from a List to an array.
Tip 2: This article can tell us that sometimes you can optimize by changing a List to an array.