Home
Search
C# List Insert ExampleUse the Insert method on List. Compare the performance of Add versus Insert.
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.
List
Insert, performance. We see how List.Insert performs. The Insert method on List has serious problems that may significantly degrade performance.
List Add
An example. 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.
Version 1 We use the Insert method to put an element at the start of the List. We specify the first argument of 0 to indicate "index 0."
Version 2 We look at code that also adds an element to the List instance, but does so at the end of the List. It uses Add().
C# program that uses List Insert
using System; using System.Collections.Generic; class Program { static void Main() { // 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
A benchmark. 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.
Benchmark
Version 1 This version of the code uses the Insert method to add an element at index 0.
Version 2 This code invokes the Add() method to append a method at the end of the List.
Result In 2020 we can see that the Insert method takes about 1000 times more time to increase the List by 100000 elements one-by-one.
C# program that times List Insert, Add
using System; using System.Collections.Generic; using System.Diagnostics; class Program { const int _max = 10; static void Main() { 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
A summary. 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.
LinkedList
Final note. 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.
For
Home
© 2007-2021 sam allen. see site info on the changelog