The cost table: pick a structure by what it costs
A data structure is a trade-off: it makes some operations cheap by making others expensive. Big-O describes how the work grows as the input grows — O(1) means "the same work no matter how big", O(n) means "work grows in step with the size", O(log n) means "doubling the input adds one step". Choosing the right collection is usually the single biggest performance decision in everyday C# code, far bigger than any micro-optimisation.
| .NET type | Index / lookup | Search | Add | Remove | Built on |
|---|---|---|---|---|---|
T[] | O(1) | O(n) | — fixed size | — | contiguous memory |
List<T> | O(1) | O(n) | O(1) amortised at end, O(n) Insert | O(1) at end, O(n) elsewhere | resizable array |
Dictionary<K,V> | O(1) avg by key | O(1) avg by key | O(1) avg | O(1) avg | hash table |
HashSet<T> | — | O(1) avg Contains | O(1) avg | O(1) avg | hash table |
Stack<T> | O(1) top only | O(n) | O(1) Push | O(1) Pop | array |
Queue<T> | O(1) front only | O(n) | O(1) Enqueue | O(1) Dequeue | circular array |
LinkedList<T> | O(n) | O(n) | O(1) at a known node | O(1) at a known node | doubly linked nodes |
SortedSet<T> / SortedDictionary<K,V> | O(log n) | O(log n) | O(log n) | O(log n) | red-black tree |
PriorityQueue<TElement,TPriority> | O(1) Peek min | O(n) | O(log n) | O(log n) Dequeue | array-backed 4-ary min-heap |
int[] data = Enumerable.Range(0, 1_000_000).ToArray();
int target = 999_999;
int linearSteps = 0;
foreach (int x in data)
{
linearSteps++;
if (x == target) break;
}
int binarySteps = 0, lo = 0, hi = data.Length - 1;
while (lo <= hi)
{
binarySteps++;
int mid = lo + (hi - lo) / 2;
if (data[mid] == target) break;
if (data[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
Console.WriteLine($"Linear search: {linearSteps} steps");
Console.WriteLine($"Binary search: {binarySteps} steps");Linear search: 1000000 steps
Binary search: 20 stepsThe same question — "where is 999,999?" — answered by O(n) and O(log n) algorithms over one million sorted numbers.
Change target to 0. Linear search now wins. Why does Big-O still say binary search is the better algorithm?
