Why is a LinkedList Generally Slower than a List?

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

    Since the other answers didn't mention this, I'm adding another.

    Although your print statement says "List Insert" you actually called List.Add, which is the one kind of "insertion" that List is actually good at. Add is a special case of just using the next element is the underlying storage array and nothing has to get moved out of the way. Try really using List.Insert instead to make it the worst case instead of the best case.

    Edit:

    To summarize, for the purposes of insertion, a list is a special-purpose data structure that is only fast at one kind of insertion: append to the end. A linked-list is a general-purpose data structure that is equally fast at inserting anywhere into the list. And there is one more detail: the linked-list has higher memory and CPU overhead so its fixed costs are higher.

    So your benchmark compares general-purpose linked-list insertion against special-purpose list append to the end and so it is not surprising that the finely-tuned optimized data structure that is being used exactly as it was intended is performing well. If you want linked list to compare favorably, you need a benchmark that list will find challenging and that means you will need to insert at the beginning or into the middle of the list.

提交回复
热议问题