csharp / beginner
Snippet
Collection Capacity Optimization
By providing an initial capacity to a List, you prevent multiple memory re-allocations as the list grows, improving performance.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections.Generic;public class EfficiencyDemo{public void PreallocateList(){// Pre-allocate space for 1000 items to avoid resizingvar data = new List<int>(1000);for (int i = 0; i < 1000; i++){data.Add(i);}}}
Breakdown
1
new List<int>(1000)
Initializes the list with an internal array of size 1000.
2
data.Add(i);
Adds items without triggering a resize operation.