TheDeveloperBlog.com


C# Array Memory Usage

Arrays are memory-efficient. Lists are built on top of arrays. Because of this, Lists use more memory to store the same data. We provide a detailed comparison of array and List memory usage.

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


Example. First, we look at the code that was tested. We focus on how the two data structures perform. The two code examples below contrast how you can use an array with more complex logic, and a List with simpler logic.

C# 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 preallocate an array and assign to it.
	int[] array = new int[60000];
	for (int i = 0; i < 60000; i++)
	{
	    array[i] = i;
	}
    }
}

In this example, the List collection is built up, one by one, at runtime. This means it may have to allocate more times or change the positions in memory during garbage collection.

List Add

Note: The int array is declared and created in one statement. Thus it will store all values in neighboring memory.

Int Array

Discussion. Here we see an example of how arrays and Lists can change performance and memory usage. The benchmarks here were taken from a more complex program, but they show the general pattern of arrays being more efficient.

And: Arrays were about 7% faster, even when other code is involved. The usage was with a data structure that looks up items.

Regarding memory usage, the int array was considerably more compact than the List generic. There can be substantial overhead when using generics instead of arrays. Please see the memory figures above.


Generics. If you need the advanced features of generics, use them. However, you might be able to convert from generics to arrays. You could store the size of the array and use it when initializing later. That way you don't have to resize anything.

Generic Class

These findings are only useful to you as a hint of how you can influence the performance of your application by changing from a List to an array. The article can't establish whether arrays or Lists are faster.

But: This article can tell us that sometimes you can optimize by changing a List to an array.


Summary. We saw a comparison of List and array memory usage in the C# language. For speed it is sometimes worthwhile to prefer regular arrays. The performance benefit is significant enough that changing your code may be worth your time.