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

后端 未结 15 1695
盖世英雄少女心
盖世英雄少女心 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条回答
  •  -上瘾入骨i
    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

提交回复
热议问题