Sam
Sam

Reputation: 986

What is faster collection.Insert(0, newItem) vs list.Add(newItem) + Sort in Winforms ListView C#?

I have a ListView that I need to update by adding an item. Using .Add() will place it on the bottom. So I can then sort it by a insert time (it's one of the fields). Another option is to use Collection.Insert(0, newItem) that will put it to the top and move everything down one index.

Read somewhere that Collection.Insert(0, newItem) may be slow for larger lists b/c of the shifting. If that is the case - what would be faster? Collection or Add + Sort?

or is there another way?

Thanks.

Upvotes: 2

Views: 2620

Answers (3)

David Merriman
David Merriman

Reputation: 6086

Insert will be faster than Add + Sort, because Sorting will involve unnecessary comparisons if your list is already sorted. But like others have said, it probably won't matter enough to care.

Upvotes: 3

Erik Philips
Erik Philips

Reputation: 54638

Unless you have millions of items, it won't matter and you're simply pre-optimizing and either will be fine. If you do have millions of items, then you are presenting to the user too many items.

Upvotes: 2

eouw0o83hf
eouw0o83hf

Reputation: 9598

If your list is going to be displayed to a user, it's probably not going to be large enough for the performance difference to be noticeable. Probably use whichever makes more sense in the context.

Upvotes: 1

Related Questions