Why is a LinkedList Generally Slower than a List?

前端 未结 6 474
旧时难觅i
旧时难觅i 2021-02-01 13:47

I started using some LinkedList’s instead of Lists in some of my C# algorithms hoping to speed them up. However, I noticed that they just felt slower. Like any good developer, I

6条回答
  •  伪装坚强ぢ
    2021-02-01 14:40

    I've done the same test with List and LinkedList inserting actual objects (Annonymous Types, actually) into the list,and Linked List is slower than List in that case as well.

    However, LinkedList DOES speed up if you insert items like this, instead of using AddFirst, and AddLast:

    LinkedList list = new LinkedList();
    LinkedListNode last = null;
    foreach(var x in aLotOfStuff)
    {
        if(last == null)
            last = list.AddFirst(x);
        else
            last = list.AddAfter(last, x);
    }
    

    AddAfter seems to be faster than AddLast. I would assume internally .NET would track the 'tail'/last object by ref, and go right to it when doing an AddLast(), but perhaps AddLast() causes it to traverse the entire list to the end?

提交回复
热议问题