Arrays Deep Dive: Static vs Dynamic (List<T> Internals)
On this page
Arrays & Dynamic Lists
Arrays are the most fundamental data structure. They store elements in Contiguous Memory, which provides O(1) access time. However, fixed-size arrays are limited. In .NET, we use List<T> to simulate a dynamic array that grows as needed.
1. How List<T> works internally
A List is just a wrapper around a static array. It has a **Capacity** (the size of the internal array) and a **Count** (the number of items you've added). When Count exceeds Capacity, the List:
- Creates a new array that is **Double** the size.
- Copies all 10 existing items to the new array.
- Deletes the old array.
2. The Cost of Resizing
Resizing is an **O(N)** operation. If you add 1 million items to a list without setting the initial capacity, the list will resize dozens of times, wasting CPU. Architect Tip: If you know you need 1000 items, use new List<int>(1000) to prevent unnecessary allocations.
4. Interview Mastery
Q: "Why is an Array better than a Linked List for simple iteration?"
Architect Answer: "Because of **CPU Cache Locality**. Since array elements are physically next to each other in memory, the CPU can pre-load the next few items into its ultra-fast L1/L2 cache. A Linked List's nodes are scattered all over the Heap, forcing the CPU to constantly wait for the RAM to find the next pointer. For simple loops, an Array can be 10x faster due to hardware optimization."
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!