Do arrays use less memory than generics? You want to look at benchmarks of Lists and arrays in real-world programs. Is it advantageous to use more complex code and logic to accomodate an array over List?
Here we ignore practical differences and 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.
using System.Collections.Generic;
class Program
{
static void Main()
{
Example t = new Example();
t.A();
t.B();
}
}
class Example
{
public void A()
{
// Compare time to build up a List individually.
List<int> l = new List<int>();
for (int i = 0; i < 60000; i++)
{
l.Add(i);
}
}
public void B()
{
// Compare time to preallocate an array and assign to it.
int[] s = new int[60000];
for (int i = 0; i < 60000; i++)
{
s[i] = i;
}
}
}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.
What I found was that the arrays were about 7% faster, even when other code is involved. The usage was with a data structure that looks up items in an array or List. [C# - Directed Acyclic Word Graph - dotnetperls.com]
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.
No. 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.
This article is one of my earliest articles on the performance differences with arrays and Lists. There is detailed information on how arrays and MSIL works at this site. [Array Types and MSIL - dotnetperls.com]
For speed, it's sometimes worthwhile to prefer regular arrays. The performance benefit is significant enough that changing your code may be worth your time, assuming the new version doesn't add too much complexity.