When using objects that have a capacity, what are some guidelines that you can use to ensure the best effeciency when using to collections? It also seems like .NET framework has set some of these capacities low. For example, I think StringBuilder has an intial capacity of 16. Does this mean that after 16 strings are inserted into the StringBuilder, the StringBuilder object is reallocated and doubled in size?
Share
With
StringBuilder, it isn’t the number of strings, but the number of characters. In general; if you can predict the length, go ahead and tell it – but since it uses doubling, there isn’t a huge overhead in reallocating occasionally if you need to juts useAddetc.In most cases, the difference will be trivial and a micro-optimisation. The biggest problem with not telling it the size is that unless the collection has a ‘trim’ method, you might have nearly double the size you really needed (if you are very unlucky).