Which algorithm is used in List to dynamically allocate memory?

后端 未结 6 1298
渐次进展
渐次进展 2021-01-18 22:18

Now I have an algorithm for dynamically allocating memory on an array:

  • If array is full I create a new array of twice the size, and copy items.
  • If arr
6条回答
  •  春和景丽
    2021-01-18 23:12

    That's basically what List (and many other languages' dynamic arrays, for that matter) does as well. The resizing factors may be different, and I think it doesn't shrink the backing array on its own when removing elements - but there's TrimToSize and you can set Capacity yourself, which probably allows more efficient strategies if client code uses this feature well. But basically, it's asymptotically equivalent.

    As for which one to use: Unless you have cold, hard data that List is suboptimal for your use case and that the difference matters (you obviously don't have this knowledge yet), you should use it. Your own implementation will be buggy, less feature-rich (cf. IEnumerable, IList, numerous methods), less optimized, less widely recognizable, not accepted by other libraries (so you may have to create expensive copies, or at least do more work than with List to interact), etc. and there is most likely absolutely nothing to be gained.

提交回复
热议问题