Arrays, memory. 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. A simple benchmark can be used to measure the memory of lists and arrays.
We focus on how the 2 data structures perform. The 2 code examples contrast how you can use an array with more complex logic, and a List with simpler logic.
Here The List collection is built up at runtime. It may have to allocate or change the positions in memory during garbage collection.
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);
}
}
}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;
}
}
}List generic: 6.172 MB
Integer array: 5.554 MBList generic: 1043.4 ms
Integer array: 980.2 ms
Discussion. Arrays and Lists can change performance and memory usage. The benchmarks were taken from a more complex program, but they show the 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.
Further For memory usage, the int array was more compact than the List generic. Arrays can lead to memory reductions over generics.
Notes, generics. 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.
Tip These findings are only useful as a hint of how you can influence performance by changing from 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).