34

Are C# lists fast? What are the good and bad sides of using lists to handle objects?

Extensive use of lists will make software slower? What are the alternatives to lists in C#?

How many objects is "too many objects" for lists?

2
  • 3
    It really depends on what you want to do with them.
    – LukeH
    Sep 16, 2009 at 14:28
  • 10
    "Fast" and "slow" are irrelevant. Relevant are "fast enough for my customer" and "too slow for my customer". Your first question should be "are lists fast enough?" You are the only one who knows who your customer is and what their performance requirements are, so only you can answer that question. You'll answer it by trying out some meaningful benchmarks and comparing them to your carefully-stated real-world customer-focussed goals. Sep 16, 2009 at 14:45

2 Answers 2

88

List<T> uses a backing array to hold items:

  • Indexer access (i.e. fetch/update) is O(1)
  • Remove from tail is O(1)
  • Remove from elsewhere requires existing items to be shifted up, so O(n) effectively
  • Add to end is O(1) unless it requires resizing, in which case it's O(n). (This doubles the size of the buffer, so the amortized cost is O(1).)
  • Add to elsewhere requires existing items to be shifted down, so O(n) effectively
  • Finding an item is O(n) unless it's sorted, in which case a binary search gives O(log n)

It's generally fine to use lists fairly extensively. If you know the final size when you start populating a list, it's a good idea to use the constructor which lets you specify the capacity, to avoid resizing. Beyond that: if you're concerned, break out the profiler...

2
  • "Add to end" even has accumulated costs of O(1) Sep 16, 2009 at 14:58
  • @Thomas: Yes, I'll mention this.
    – Jon Skeet
    Sep 16, 2009 at 15:16
13

Compared to what?

  • If you mean List<T>, then that is essentially a wrapper around an array; so fast to read/write by index, relatively fast to append (since it allows extra space at the end, doubling in size when necessary) and remove from the end, but more expensive to do other operations (insert/delete other than the end)
  • An array is again fast by index, but fixed size (no append/delete)
  • Dictionary<,> etc offer better access by key

A list isn't intrinsically slow; especially if you know you always need to look at all the data, or can access it by index. But for large lists it may be better (and more convenient) to search via a key. There are various dictionary implementations in .NET, each with different costs re size / performance.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.