How and when to abandon the use of arrays in C#?

后端 未结 15 1703
盖世英雄少女心
盖世英雄少女心 2020-12-13 02:58

I\'ve always been told that adding an element to an array happens like this:

An empty copy of the array+1element is created and then the data from t

15条回答
  •  执念已碎
    2020-12-13 03:42

    This really depends on what you mean by "add."

    If you mean:

    T[] array;
    int i;
    T value;
    ...
    if (i >= 0 && i <= array.Length)
        array[i] = value;
    

    Then, no, this does not create a new array, and is in-fact the fastest way to alter any kind of IList in .NET.

    If, however, you're using something like ArrayList, List, Collection, etc. then calling the "Add" method may create a new array -- but they are smart about it, they don't just resize by 1 element, they grow geometrically, so if you're adding lots of values only every once in a while will it have to allocate a new array. Even then, you can use the "Capacity" property to force it to grow before hand, if you know how many elements you're adding (list.Capacity += numberOfAddedElements)

提交回复
热议问题