When should I use a List vs a LinkedList

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

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

相关标签:
15条回答
  • 2020-11-22 15:23

    So many average answers here...

    Some linked list implementations use underlying blocks of pre allocated nodes. If they don't do this than constant time / linear time is less relevant as memory performance will be poor and cache performance even worse.

    Use linked lists when

    1) You want thread safety. You can build better thread safe algos. Locking costs will dominate a concurrent style list.

    2) If you have a large queue like structures and want to remove or add anywhere but the end all the time . >100K lists exists but are not that common.

    0 讨论(0)
  • 2020-11-22 15:25

    In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.

    LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine.

    List<T> also offers a lot of support methods - Find, ToArray, etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.

    0 讨论(0)
  • 2020-11-22 15:25

    This is adapted from Tono Nam's accepted answer correcting a few wrong measurements in it.

    The test:

    static void Main()
    {
        LinkedListPerformance.AddFirst_List(); // 12028 ms
        LinkedListPerformance.AddFirst_LinkedList(); // 33 ms
    
        LinkedListPerformance.AddLast_List(); // 33 ms
        LinkedListPerformance.AddLast_LinkedList(); // 32 ms
    
        LinkedListPerformance.Enumerate_List(); // 1.08 ms
        LinkedListPerformance.Enumerate_LinkedList(); // 3.4 ms
    
        //I tried below as fun exercise - not very meaningful, see code
        //sort of equivalent to insertion when having the reference to middle node
    
        LinkedListPerformance.AddMiddle_List(); // 5724 ms
        LinkedListPerformance.AddMiddle_LinkedList1(); // 36 ms
        LinkedListPerformance.AddMiddle_LinkedList2(); // 32 ms
        LinkedListPerformance.AddMiddle_LinkedList3(); // 454 ms
    
        Environment.Exit(-1);
    }
    

    And the code:

    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    
    namespace stackoverflow
    {
        static class LinkedListPerformance
        {
            class Temp
            {
                public decimal A, B, C, D;
    
                public Temp(decimal a, decimal b, decimal c, decimal d)
                {
                    A = a; B = b; C = c; D = d;
                }
            }
    
    
    
            static readonly int start = 0;
            static readonly int end = 123456;
            static readonly IEnumerable<Temp> query = Enumerable.Range(start, end - start).Select(temp);
    
            static Temp temp(int i)
            {
                return new Temp(i, i, i, i);
            }
    
            static void StopAndPrint(this Stopwatch watch)
            {
                watch.Stop();
                Console.WriteLine(watch.Elapsed.TotalMilliseconds);
            }
    
            public static void AddFirst_List()
            {
                var list = new List<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (var i = start; i < end; i++)
                    list.Insert(0, temp(i));
    
                watch.StopAndPrint();
            }
    
            public static void AddFirst_LinkedList()
            {
                var list = new LinkedList<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (int i = start; i < end; i++)
                    list.AddFirst(temp(i));
    
                watch.StopAndPrint();
            }
    
            public static void AddLast_List()
            {
                var list = new List<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (var i = start; i < end; i++)
                    list.Add(temp(i));
    
                watch.StopAndPrint();
            }
    
            public static void AddLast_LinkedList()
            {
                var list = new LinkedList<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (int i = start; i < end; i++)
                    list.AddLast(temp(i));
    
                watch.StopAndPrint();
            }
    
            public static void Enumerate_List()
            {
                var list = new List<Temp>(query);
                var watch = Stopwatch.StartNew();
    
                foreach (var item in list)
                {
    
                }
    
                watch.StopAndPrint();
            }
    
            public static void Enumerate_LinkedList()
            {
                var list = new LinkedList<Temp>(query);
                var watch = Stopwatch.StartNew();
    
                foreach (var item in list)
                {
    
                }
    
                watch.StopAndPrint();
            }
    
            //for the fun of it, I tried to time inserting to the middle of 
            //linked list - this is by no means a realistic scenario! or may be 
            //these make sense if you assume you have the reference to middle node
    
            //insertion to the middle of list
            public static void AddMiddle_List()
            {
                var list = new List<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (var i = start; i < end; i++)
                    list.Insert(list.Count / 2, temp(i));
    
                watch.StopAndPrint();
            }
    
            //insertion in linked list in such a fashion that 
            //it has the same effect as inserting into the middle of list
            public static void AddMiddle_LinkedList1()
            {
                var list = new LinkedList<Temp>();
                var watch = Stopwatch.StartNew();
    
                LinkedListNode<Temp> evenNode = null, oddNode = null;
                for (int i = start; i < end; i++)
                {
                    if (list.Count == 0)
                        oddNode = evenNode = list.AddLast(temp(i));
                    else
                        if (list.Count % 2 == 1)
                            oddNode = list.AddBefore(evenNode, temp(i));
                        else
                            evenNode = list.AddAfter(oddNode, temp(i));
                }
    
                watch.StopAndPrint();
            }
    
            //another hacky way
            public static void AddMiddle_LinkedList2()
            {
                var list = new LinkedList<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (var i = start + 1; i < end; i += 2)
                    list.AddLast(temp(i));
                for (int i = end - 2; i >= 0; i -= 2)
                    list.AddLast(temp(i));
    
                watch.StopAndPrint();
            }
    
            //OP's original more sensible approach, but I tried to filter out
            //the intermediate iteration cost in finding the middle node.
            public static void AddMiddle_LinkedList3()
            {
                var list = new LinkedList<Temp>();
                var watch = Stopwatch.StartNew();
    
                for (var i = start; i < end; i++)
                {
                    if (list.Count == 0)
                        list.AddLast(temp(i));
                    else
                    {
                        watch.Stop();
                        var curNode = list.First;
                        for (var j = 0; j < list.Count / 2; j++)
                            curNode = curNode.Next;
                        watch.Start();
    
                        list.AddBefore(curNode, temp(i));
                    }
                }
    
                watch.StopAndPrint();
            }
        }
    }
    

    You can see the results are in accordance with theoretical performance others have documented here. Quite clear - LinkedList<T> gains big time in case of insertions. I haven't tested for removal from the middle of list, but the result should be the same. Of course List<T> has other areas where it performs way better like O(1) random access.

    0 讨论(0)
  • 2020-11-22 15:26

    When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.

    0 讨论(0)
  • 2020-11-22 15:31

    I do agree with most of the point made above. And I also agree that List looks like a more obvious choice in most of the cases.

    But, I just want to add that there are many instance where LinkedList are far better choice than List for better efficiency.

    1. Suppose you are traversing through the elements and you want to perform lot of insertions/deletion; LinkedList does it in linear O(n) time, whereas List does it in quadratic O(n^2) time.
    2. Suppose you want to access bigger objects again and again, LinkedList become very more useful.
    3. Deque() and queue() are better implemented using LinkedList.
    4. Increasing the size of LinkedList is much easier and better once you are dealing with many and bigger objects.

    Hope someone would find these comments useful.

    0 讨论(0)
  • 2020-11-22 15:33

    Edit

    Please read the comments to this answer. People claim I did not do proper tests. I agree this should not be an accepted answer. As I was learning I did some tests and felt like sharing them.

    Original answer...

    I found interesting results:

    // Temporary class to show the example
    class Temp
    {
        public decimal A, B, C, D;
    
        public Temp(decimal a, decimal b, decimal c, decimal d)
        {
            A = a;            B = b;            C = c;            D = d;
        }
    }
    

    Linked list (3.9 seconds)

            LinkedList<Temp> list = new LinkedList<Temp>();
    
            for (var i = 0; i < 12345678; i++)
            {
                var a = new Temp(i, i, i, i);
                list.AddLast(a);
            }
    
            decimal sum = 0;
            foreach (var item in list)
                sum += item.A;
    

    List (2.4 seconds)

            List<Temp> list = new List<Temp>(); // 2.4 seconds
    
            for (var i = 0; i < 12345678; i++)
            {
                var a = new Temp(i, i, i, i);
                list.Add(a);
            }
    
            decimal sum = 0;
            foreach (var item in list)
                sum += item.A;
    

    Even if you only access data essentially it is much slower!! I say never use a linkedList.




    Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list)

    Linked List (51 seconds)

            LinkedList<Temp> list = new LinkedList<Temp>();
    
            for (var i = 0; i < 123456; i++)
            {
                var a = new Temp(i, i, i, i);
    
                list.AddLast(a);
                var curNode = list.First;
    
                for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it
                    curNode = curNode.Next;
    
                list.AddAfter(curNode, a); // Insert it after
            }
    
            decimal sum = 0;
            foreach (var item in list)
                sum += item.A;
    

    List (7.26 seconds)

            List<Temp> list = new List<Temp>();
    
            for (var i = 0; i < 123456; i++)
            {
                var a = new Temp(i, i, i, i);
    
                list.Insert(i / 2, a);
            }
    
            decimal sum = 0;
            foreach (var item in list)
                sum += item.A;
    

    Linked List having reference of location where to insert (.04 seconds)

            list.AddLast(new Temp(1,1,1,1));
            var referenceNode = list.First;
    
            for (var i = 0; i < 123456; i++)
            {
                var a = new Temp(i, i, i, i);
    
                list.AddLast(a);
                list.AddBefore(referenceNode, a);
            }
    
            decimal sum = 0;
            foreach (var item in list)
                sum += item.A;
    

    So only if you plan on inserting several items and you also somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time.

    0 讨论(0)
提交回复
热议问题