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
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.
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.
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).
The Insert method is used to insert an item into the middle of the list.
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 insert
it 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With