Darkgaze
Darkgaze

Reputation: 2573

How to set count of c# without altering capacity?

I know exactly how many items I want to keep in a list, they are ordered, I only need it to finish at an specific index I know, but I don't want to alter the capacity or use TrimExcess in order to make it smaller, otherwise after adding an item again it will double the size of the list again.

How can I set the Count instead of using Remove or RemoveAt or RemoveRange?.

My priority is optimization of speed for this operation.

Important: I know I can use an array, but I am not allowed. Also, I'm adding items and removing them all the time. I just want the capacity to stay around a similar amount which I don't know exactly but it will stabilize.

Upvotes: 0

Views: 800

Answers (2)

PMF
PMF

Reputation: 17338

If you remove elements, the Capacity won't change. So if you don't use TrimExcess(), the Capacity will only ever increase (to the maximum you ever used for this list). So there's no performance penalty in removing elements again. You can set the initial capacity in the constructor, which is a good idea if you know how many elements you'll be using (or have an estimate for it), because that will remove the overload of the doubling while initially building up the list.

Note: Insert/Remove in a list is still O(n), because the elements eventually need to be compied around (unless you operate only at the tail end of the list).

Upvotes: 2

James Harcourt
James Harcourt

Reputation: 6399

Use an array and (in C# 8.0 onwards) use Indices and Ranges with slicing. https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges

Upvotes: 0

Related Questions