List<>.Add & List<>.Reverse vs List<>.Insert

Hey, another question here.

In the lecture we added to the pathNodeList and reversed it with List<>.Add(), and List<>.Reverse() respectively.

I know we could also use List<>.Insert() and not have to worry about reversing it later, but is this a preference thing, or is there a performance reason to not use List<>.Insert() in this case?

Cheers!

I think you’d really have to benchmark it if you want to know the performance impact. Reverse recreates the array from back to front, while Insert shifts all the items from index onwards on by 1 position, and then inserts the value. With Insert you do this every time, while Reverse only happens once - but it does include the Add.

I (very crudely) benchmarked 100,000 items with Insert and Reverse (and Add then Reverse) a 100 times and this is what I found:

                          Min            Max            Avg
Insert Time:              864ms          1537ms         1219ms
Reverse Time:               0ms             1ms            0ms
Add + Reverse Time:         0ms             6ms            0ms

Bare in mind that this was pretty crudely done, but I did run this a couple of times and the results were pretty much the same

Looks like you should not use Insert

2 Likes

This is the second time you’ve come to my aid. Thank you, @bixarrio , I really appreciate it.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms