Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List.Insert have any performance penalty?

Tags:

Given a list:

List<object> SomeList = new List<object>(); 

Does doing:

SomeList.Insert(i, val); 

Vs.

SomeList.Add(val); 

Has any performance penalty? If it does, how it depends on:
- i - insertion index
- SomeList.Count - The size of the list

like image 553
Yosi Dahari Avatar asked Sep 03 '13 08:09

Yosi Dahari


People also ask

Is list slower than array?

Slower Search Time:Linked list have slower search times than arrays as random access is not allowed. Unlike arrays where the elements can be search by index, linked list require iteration.

Is list more efficient than array?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.

Are lists faster than arrays?

Voilà, Arrays can be up to 97% faster than Lists (obvious, this is a synthetic test and in real tests the difference will be smaller).

What does list insert Do C#?

The Insert method is used to insert an item into the middle of the list.


2 Answers

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface using an array whose size is dynamically increased as required.

(source)

Meaning that the internal data is stored as an Array, and so it is likely that to perform the insertit will need to move all the elements over to make room, thus its complexity is O(N), while add is a (amortised) constant time O(1) operation, so yes.

Summary - Yes, it will almost always be slower, and it will get slower the larger your list gets.

like image 184
Karthik T Avatar answered Sep 19 '22 18:09

Karthik T


When in doubt, perform an empirical experiment:

List<object> SomeList = new List<object>();  Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 100000; i++)     SomeList.Insert(0, String.Empty); sw.Stop(); Console.WriteLine(sw.Elapsed.TotalMilliseconds); sw.Reset();  SomeList = new List<object>(); sw.Start(); for (var i = 0; i < 100000; i++)     SomeList.Add(String.Empty); sw.Stop(); Console.WriteLine(sw.Elapsed.TotalMilliseconds); 

The Insert takes 2800ms on my machine; the Add takes 0.8ms. So yes, Insert is much less performant.

like image 39
pattermeister Avatar answered Sep 20 '22 18:09

pattermeister