Why is a LinkedList Generally Slower than a List?

前端 未结 6 486
旧时难觅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:19

    Keep in mind that you've got lists of primitives. For List this is very simple because it creates a whole array of int and it's very easy for it to shift these down when it doesn't have to allocate more memory.

    Contrast this to a LinkedList that always must allocate memory to wrap the ints. Thus I think the memory allocation is probably what's contributing the most to your time. If you already had the node allocated, it should be faster overall. I'd try an experiment with the overload of AddFirst that takes a LinkedListNode to verify (that is, create the LinkedListNode outside of the scope of the timer, just time the add of it).

    Iterating is similar, it's much more efficient to go to the next index in an internal array than to follow links.

提交回复
热议问题