C # usage and difference of arrays, ArrayList, List, and Dictionary,
Preface
I often encounter C # arrays, ArrayList, List, and Dictionary access data in my work. However, I still don't know how to choose which type to store data. So I took a good look at their usage and comparison. Here I will summarize them and update them later.
Initialization
Array:
int[] buff = new int[6];
ArrayList:
ArrayList buff = new ArrayList();
List:
List<int> buff = new List<int>();
Dictionary:
Dictionary<int,string> buff = new Dictionary<int,string>;
Analysis and Comparison
From the several types initialized above, we can see that they all belong to the reference type. Array, List, and Dictionary must specify their element types during initialization, while ArrayList does not. Only the array size is set during initialization.
Array: the size and type of the array must be specified during initialization. It is stored continuously in the memory, so we can see that the index speed of the array is very fast. After determining the length and type of the array, it is better to select an array to store data. It is not suitable for insert operations.
ArrayList: you do not need to specify its size and type during initialization. It can store different data types, but it may cause packing and unpacking during the storage and acquisition process, reducing the performance. Easy to insert.
List: its type must be specified during initialization, but the size does not need to be specified. Therefore, it does not cause packing and unpacking operations during access like ArraryList. In the case of the same type, the performance of List and array is equivalent. Easy to insert.
Dictionary: You must specify its type during initialization, and specify a Key that is unique. Because of this, the indexing speed of Dictionary is very fast. However, because a Key is added, the memory occupied by the Dictionary is larger than that of other types. The Key is used to search for elements. The order of elements is not fixed.
| Type |
Confirm size |
Confirm type |
Indexing speed |
Performance |
| Array |
Y |
Y |
Soon |
Highest |
| ArrayList |
N |
N |
Average |
Low |
| List |
N |
Y |
Soon |
High |
| Dictionary |
N |
Y |
Fastest |
Average |
NOTE: If any of the above descriptions are inappropriate, please leave a message, share your knowledge, and grow together!