So pretty much every question related to capacity in ArrayList is how to use it or (oddly) access it and I am quite familiar with that information. What I am interested in whether it is actually worth using the ArrayList constructor that sets capacity if you happen to know or have a rough idea how many items will be in the ArrayList?
Are there any comprehensive benchmarks comparing how long it takes to just use naive adding of elements to an ArrayList versus pre-setting the capacity of an ArrayList?
I have nothing substantial to add to ruakh's answer, but here's a quick test function. I keep a scrap project around for writing little tests like these. Adjust the sourceSize to something representative of your data, and you can get a rough idea of the magnitude of the effect. As shown, I saw about a factor of 2 between them.
Output:
Obviously for any specific application you'd have to test any performance adjustments to determine if they are in fact optimizations (and if they are in fact necessary), but there are some times that setting the capacity explicitly can be worthwhile. For example:
ArrayList internals uses simple arrays to store its elements, if the number of elements exceeds the capacity of the underlying array, a resize effort is need. So, in the case you know how many items will your List contain, you can inform ArrayList to use an array of the needed size so the resize logic won't be needed or executed.