In my code I sometimes need to create large collections of objects. Please note that I need collections and not arrays, because I might need to add items later.
What is an efficient way to do this?
Let’s assume that objects are quite simple and can be created fast with default parameter-less constructor. Something like this:
class MyObject
{
private int a;
public int A
{
get { return a; }
set { a = value; }
}
}
Sure, I can create my collection like this:
List<MyObject> list = new List<MyObject>(knownNumberOfItems);
for (int i = 0; i < knownNumberOfItems; i++)
list.Add(new MyObject());
But maybe there is a better way to do the same?
Summary from the discussion:
- There is no faster way to do this for reference types. You might get some performance improvements using value types.
- Try allocating more space initially to reduce number of reallocations when new items are added later.
There’s no faster way that I’m familiar with. I’d personally use braces around the body of the
forloop, but as a way of creating a list of a given size, populated with distinct references to new objects, that’s about it. The important part is that you specified the size of the list to start with, so thoseAddcalls won’t need to reallocate anything internally.If you’re potentially going to add items later on, you may want to give a slightly bigger size, of course.
It feels unlikely that this is a bottleneck in your system though – and as always, readability should be your primary concern (and isn’t an issue here other than the change I’ve suggested) with performance being constantly measured, but only causing change at a low level when a concern has been validated by measurements.