It will be interesting to all of you to think about what is the underlying implementation of List and Dictionary in .net core.These data structures are those that are used mostly in our codes,so,it is important to know more about them in detail.
It will be a suprise if you know that List uses Array in its underlying implementation.So,one fact about array is ,it is an immutable data structure in size.Array has fixed size and it is specified in initialization step.So for adding an extra member,you have to create a new array ,copy the older array with the new member in the new array.
Actually,this happens in the List everytime you add a new member to it,It copies the underlying array with the new member into a new array.So,Imagine that you repeatedly add new member to a List that has a large amount of members.For every add operation ,it copies whole array and allocate a new one.
What about Dictionary?
In fact,Dictionary in it’s underlying implementation uses array too!whenever you add a new member,it generate the corresponding hash code for specified key,then add it to a new array by copying the older array with new member to a new array.
Additionally,when you want to find a value by key,it generates corresponding hashcode to find a reference to the item in the array.If it’s hashcode matches and the key was equal to the specifed key the match occured,but if the hashcode is equall and keys are not equal,conflict has happened,so it has to go to find other hashcode and key matches.In the worst case it has to go through all the array.
In Conclusion,use array instead of List as mush as it possible.Another point is that if you are using List,instead of colling repeatedly list.Add,that’s better to use list.AddRange to minimize copy overhead in memory.