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

后端 未结 15 1653
盖世英雄少女心
盖世英雄少女心 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:44

    In general, I prefer to avoid array usage. Just use List<T>. It uses a dynamically-sized array internally, and is fast enough for most usage. If you're using multi-dimentional arrays, use List<List<List<T>>> if you have to. It's not that much worse in terms of memory, and is much simpler to add items to.

    If you're in the 0.1% of usage that requires extreme speed, make sure it's your list accesses that are really the problem before you try to optimize it.

    0 讨论(0)
  • 2020-12-13 03:48

    Generally, if you must have the BEST indexed lookup performance it's best to build a List first and then turn it into a array thus paying a small penalty at first but avoiding any later. If the issue is that you will be continually adding new data and removing old data then you may want to use a ArrayList or List for convenience but keep in mind that they are just special case Arrays. When they "grow" they allocate a completely new array and copy everything into it which is extremely slow.

    ArrayList is just an Array which grows when needed. Add is amortized O(1), just be careful to make sure the resize won't happen at a bad time. Insert is O(n) all items to the right must be moved over. Remove is O(n) all items to the right must be moved over.

    Also important to keep in mind that List is not a linked list. It's just a typed ArrayList. The List documentation does note that it performs better in most cases but does not say why.

    The best thing to do is to pick a data structure which is appropriate to your problem. This depends one a LOT of things and so you may want to browse the System.Collections.Generic Namespace.

    In this particular case I would say that if you can come up with a good key value Dictionary would be your best bet. It has insert and remove that approaches O(1). However, even with a Dictionary you have to be careful not to let it resize it's internal array (an O(n) operation). It's best to give them a lot of room by specifying a larger-then-you-expect-to-use initial capacity in the constructor.

    -Rick

    0 讨论(0)
  • 2020-12-13 03:48

    This forum post might or might not be of some use to you regarding efficiency of various array types: C# arrays - multidimensional vs lexicographic

    0 讨论(0)
提交回复
热议问题