C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# program that uses List Insert
using System.Collections.Generic;
class Program
{
static void Main()
{
List<long> list = new List<long>();
for (long i = 0; i < 100000; i++)
{
list.Insert(0, i);
}
}
}
C# program that uses List Add
using System.Collections.Generic;
class Program
{
static void Main()
{
List<long> list = new List<long>();
for (long i = 0; i < 100000; i++)
{
list.Add(i);
}
}
}
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"));
}
}
Output
1181336470.00 ns Insert
1002800.00 ns Add