Set List initial capacity to improve speed

FYI… setting capacity on a List<> when creating it can avoid a lot of expensive resizing operations.

Even if we don’t know exactly how big the list will be, a somewhat accurate estimate can still likely improve speed. Note though the higher our estimate is above the final list size the more unnecessary memory will be allocated but this speed v memory trade-off could be acceptable in many apps.

Some awesome benchmarks (originally published on LinkedIn) from Roger Maza below. Click on the image for a larger view in a new tab.

And note… it’s the same idea with StringBuilder… we can set the capacity at creation time to improve speed.