When should I use a List vs a LinkedList

后端 未结 15 2265
挽巷
挽巷 2020-11-22 14:50

When is it better to use a List vs a LinkedList?

15条回答
  •  遥遥无期
    2020-11-22 15:23

    Thinking of a linked list as a list can be a bit misleading. It's more like a chain. In fact, in .NET, LinkedList does not even implement IList. There is no real concept of index in a linked list, even though it may seem there is. Certainly none of the methods provided on the class accept indexes.

    Linked lists may be singly linked, or doubly linked. This refers to whether each element in the chain has a link only to the next one (singly linked) or to both the prior/next elements (doubly linked). LinkedList is doubly linked.

    Internally, List is backed by an array. This provides a very compact representation in memory. Conversely, LinkedList involves additional memory to store the bidirectional links between successive elements. So the memory footprint of a LinkedList will generally be larger than for List (with the caveat that List can have unused internal array elements to improve performance during append operations.)

    They have different performance characteristics too:

    Append

    • LinkedList.AddLast(item) constant time
    • List.Add(item) amortized constant time, linear worst case

    Prepend

    • LinkedList.AddFirst(item) constant time
    • List.Insert(0, item) linear time

    Insertion

    • LinkedList.AddBefore(node, item) constant time
    • LinkedList.AddAfter(node, item) constant time
    • List.Insert(index, item) linear time

    Removal

    • LinkedList.Remove(item) linear time
    • LinkedList.Remove(node) constant time
    • List.Remove(item) linear time
    • List.RemoveAt(index) linear time

    Count

    • LinkedList.Count constant time
    • List.Count constant time

    Contains

    • LinkedList.Contains(item) linear time
    • List.Contains(item) linear time

    Clear

    • LinkedList.Clear() linear time
    • List.Clear() linear time

    As you can see, they're mostly equivalent. In practice, the API of LinkedList is more cumbersome to use, and details of its internal needs spill out into your code.

    However, if you need to do many insertions/removals from within a list, it offers constant time. List offers linear time, as extra items in the list must be shuffled around after the insertion/removal.

提交回复
热议问题