I am looping through a potentially huge (millions of items) dataset (stored on disk) and pulling out selected items which I am adding to a List<T>
. When I add an item to the list, I put a lock around it, as there are other threads accessing the list.
I am trying to decide between two possible implementations:
1) Lock the list every time I need to add an item.
2) Use a temporary list that I add items to as I find them, and then use List<T>.AddRange()
to add the items in that list in a chunk (e.g. when I have found 1000 matches). This results in needing to request a lock on the list less often, but if AddRange() only increases the capacity enough to exactly accommodate the new items then the list will end up being re-sized a lot more times.
My question is this: As I understand it, adding items one at a time will cause the internal capacity of a List<T>
to double in size every time the capacity is reached, but I don't know how List<T>.AddRange()
behaves. I would assume that it only adds enough capacity to accommodate the new items, but I can't find any way to confirm this. The description of how the capacity is increased on MSDN is almost identical for Add() and AddRange(), except that for AddRange it says that if the new count is greater than the capacity the capacity is increased rather than if the Count is already the same as the capacity.
To me this reads as if using AddRange() to add enough items to go over the current capacity would cause the capacity to be increased in the same way that going over the current capacity using Add() would.
So, will adding items using List<T>.AddRange()
in a chunk large enough to exceed the current capacity cause the capacity to increase only enough to accommodate the new items, or will it cause the capacity to double? Or does it do something else that I've not even considered?
Hopefully this is clear enough without any code samples as it is a general question about how List<T>
is implemented, but if not I will add any that will make my question clearer.
As mentioned, I've read the MSDN documentation and couldn't find a clear answer. I searched for any similar questions on here as well and couldn't find any, but if there's one I've missed please point me to it!