Given a List<T> in c# is there a way to extend it (within its capacity) and set the new elements to null? I’d like something that works like a memset. I’m not looking for sugar here, I want fast code. I known that in C the operation could be done in something like 1-3 asm ops per entry.
The best solution I’ve found is this:
list.AddRange(Enumerable.Repeat(null, count-list.Count));
however that is c# 3.0 (<3.0 is preferred) and might be generating and evaluating an enumerator.
My current code uses:
while(list.Count < lim) list.Add(null);
so that’s the starting point for time cost.
The motivation for this is that I need to set the n’th element even if it is after the old Count.
The simplest way is probably by creating a temporary array:
Where
sizeis the required new size, andcountis the count of items in the list.However, for relatively large values of(size - count, this can have bad performance, since it can cause the list to reallocate multiple times.*) It also has the disadvantage of allocating an additional temporary array, which, depending on your requirements, may not be acceptable. You could mitigate both issues at the expense of more explicit code, by using the following methods:The only C# 3.0 here is the use of the ‘
this‘ modifier to make them extension methods. Remove the modifier and it will work in C# 2.0.Unfortunately, I never compared the performance of the two versions, so I don’t know which one is better.
Oh, and did you know you could resize an array by calling
Array.Resize<T>? I didn’t know that. 🙂Update:
(
*) Usinglist.AddRange(array)will not cause an enumerator to be used. Looking further through Reflector showed that the array will be casted toICollection<T>, and theCountproperty will be used so that allocation is done only once.