C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
How is this method on the List type implemented in the .NET Framework? It requires an index argument. We look at both the usage of RemoveAt and its implementation.
Example. In this program we specify that a List be instantiated with three strings: "dot", "net" and "deves". Next, we remove the string at index 1, which is the second string. The List now contains only two strings: "dot" and "deves".
C# program that uses RemoveAt using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<string>(); list.Add("dot"); list.Add("net"); list.Add("deves"); list.RemoveAt(1); foreach (string element in list) Console.WriteLine(element); } } Output dot deves
Discussion. My reason for looking at the RemoveAt method was to determine its implementation. Unfortunately, when you call RemoveAt, all the element following the index you remove will be copied and shifted forward.
This is not efficient. If you want to remove an element but eliminate copying, you could simply assign it to null or default(T). Your other code would then have to handle null elements.
Also: The Insert method on List suffers from a similar performance drawback. It causes excessive element copying.
Summary. We tested RemoveAt and looked at its internals. RemoveAt will cause all following elements in the list to be copied to new locations in memory. Calling RemoveAt frequently on a large list reduces performance.
Instead: Using a LinkedList or a scheme where null or default elements are treated specially is recommended.