using System; using System.Collections.Generic; using System.Diagnostics; class Program { static void Main() { int size = 1000000; int[] arr = new int[size]; List<int> list = new List<int>(size); for (int i = 0; i < size; i++) { arr[i] = i; list.Add(i); } Stopwatch sw = new Stopwatch(); sw.Start(); int sumArr = 0; for (int i = 0; i < size; i++) { sumArr += arr[i]; } sw.Stop(); Console.WriteLine($"Array access time: {sw.ElapsedMilliseconds} ms"); sw.Restart(); int sumList = 0; for (int i = 0; i < size; i++) { sumList += list[i]; } sw.Stop(); Console.WriteLine($"List access time: {sw.ElapsedMilliseconds} ms"); } }
Arrays provide faster indexed access than Lists because arrays are stored contiguously in memory and have no overhead of dynamic resizing or extra indirection. Lists have some overhead due to internal management.
Arrays allow direct access to any element by index in constant time, which is ideal when you need fast random access. Linked lists require traversal, making random access slower.
int[] arr = new int[3] {1, 2, 3}; int[] newArr = new int[5]; for (int i = 0; i < arr.Length; i++) { newArr[i] = arr[i]; } Console.WriteLine(string.Join(",", newArr));
The original loop uses <= arr.Length which causes the index to go out of bounds because valid indices are 0 to arr.Length - 1. Changing it to < arr.Length fixes the error.
Dynamic arrays (like List in C#) allow fast random access and amortized efficient insertions/deletions at the end. Insertions/deletions in the middle are slower but better than arrays. Linked lists have slow random access. Balanced trees are good for ordered data but slower for indexed access.
Arrays allocate a single block of contiguous memory for all elements. Linked lists allocate memory for each node separately, scattered in memory, connected by pointers.
