DotNet.SystemCollections.Analyzers icon indicating copy to clipboard operation
DotNet.SystemCollections.Analyzers copied to clipboard

Flag developers who use dynamic collections (List, HashSet, Dictionary) without setting an initial capacity.

Open Kavignon opened this issue 5 years ago • 0 comments

SITUATION:

The software developer is creating a temporary list such as List<MySuperCoolObjectType> someList = new List<MySuperCoolObjectType>();

and has some logic to determine whether or not they should add an element to said list such as

for(int i = 0; i < someFixedInteger = 10_000; i++) { if(somePredicateFunction(i)) { someList.Add(i); } }

This code looks benign, but it isn't. Here, the CLR will have to reallocate memory for the underneath array inside the list. In total, here, the list will be reallocated 13 times to match the current required size. Furthermore, we're allocating more than it requires because, in total, it'll have a capacity of 16, 384 objects.

By making the current change,

List<MySuperCoolObjectType> someList = new List<MySuperCoolObjectType>(10_000);

we get the following benefits:

  • Memory allocation performed only once
  • The maximum size of the list matches the expected fixed value
  • Even if only half of the list is filled, we're wasting less memory because we're controlling the allocation

Kavignon avatar Jan 06 '20 17:01 Kavignon