Insert
The Insert
method puts an element into a C# List
. Any position can be specified—we can (for example) insert an element to the start of the List
.
With a benchmark, we see how List.Insert
performs. The Insert
method on List
has serious problems that may significantly degrade performance.
The Insert()
method can place an element anywhere inside a List
. But it should not be used when the Add()
method is acceptable—we can sometimes use either method.
Insert
method to put an element at the start of the List
. We specify the first argument of 0 to indicate "index 0."List
instance, but does so at the end of the List
. It uses Add()
.using System; using System.Collections.Generic; // Version 1: use Insert. var list1 = new List<string>() { "bird" }; list1.Insert(0, "frog"); // Version 2: use Add. var list2 = new List<string>() { "bird" }; list2.Add("cat"); // Print results. Console.WriteLine(string.Join(",", list1)); Console.WriteLine(string.Join(",", list2));frog,bird bird,cat
Consider this benchmark: it has two versions of code that do slightly different things. But each version increases the size of the List
by 100000 elements.
Insert
method to add an element at index 0.Add()
method to append a method at the end of the List
.Insert
method takes about 1000 times more time to increase the List
by 100000 elements one-by-one.using System; using System.Collections.Generic; using System.Diagnostics; const int _max = 10; var s1 = Stopwatch.StartNew(); // Version 1: insert at index 0. for (int i = 0; i < _max; i++) { List<long> list = new List<long>(); for (long z = 0; z < 100000; z++) { list.Insert(0, i); } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use Add() method. for (int i = 0; i < _max; i++) { List<long> list = new List<long>(); for (long z = 0; z < 100000; z++) { list.Add(i); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));1181336470.00 ns Insert 1002800.00 ns Add
The List
type is not optimized for Insert
, but is fast for Add. Use LinkedList
or another data structure if you need to insert items at the start.
Often you can sort the elements later if you need a specific order. We can call Add()
and then scan through the List
backwards, avoiding Insert
calls.