Dimo Chanev
Dimo Chanev

Reputation: 129

Is in C# List something like vector.reserve(n) in C++

When adding a lot of elements in System.Collections.Generic.List<T> it is running slow because when nums increases capacity it must copy all elements. In C++ this is fixed with vector.reserve(n). How can i do that in C#?

Upvotes: 10

Views: 7988

Answers (1)

Anton Savin
Anton Savin

Reputation: 41331

Use Capacity property:

list.Capacity = n;

or you can set initial capacity via the constructor:

var list = new List<int>(n);

Upvotes: 24

Related Questions