Search code examples
c#c++listusingstdvector

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#?


Solution

  • Use Capacity property:

    list.Capacity = n;
    

    or you can set initial capacity via the constructor:

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