When should I use a List vs a LinkedList

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

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

15条回答
  •  猫巷女王i
    2020-11-22 15:33

    My previous answer was not enough accurate. As truly it was horrible :D But now I can post much more useful and correct answer.


    I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: https://github.com/ukushu/DataStructuresTestsAndOther.git

    Short results:

    • Array need to use:

      • So often as possible. It's fast and takes smallest RAM range for same amount information.
      • If you know exact count of cells needed
      • If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
      • If needed high Random Access speed
    • List need to use:

      • If needed to add cells to the end of list (often)
      • If needed to add cells in the beginning/middle of the list (NOT OFTEN)
      • If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
      • If needed high Random Access speed
    • LinkedList need to use:

      • If needed to add cells in the beginning/middle/end of the list (often)
      • If needed only sequential access (forward/backward)
      • If you need to save LARGE items, but items count is low.
      • Better do not use for large amount of items, as it's use additional memory for links.

    More details:

    Interesting to know:

    1. LinkedList internally is not a List in .NET. It's even does not implement IList. And that's why there are absent indexes and methods related to indexes.

    2. LinkedList is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for LinkedList than for List or Array.

    3. List in .Net is Java's alternative of ArrayList. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size < 85000 bytes -- this provides a very compact and fast-access representation in memory.

    4. Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes.

提交回复
热议问题