Mark Justison wrote:Why would sb3 be the only StringBuilder that is updating its capacity? Am I missing something in my code?
The capacity is one of the internals of the
StringBuilder. And as Paul mentioned the capacity will not be updated on every occasion.
The StringBuilder uses behind the scenes a
char array to store its content. If the size of the array is not big enough to store new content, the capacity is increased and a new array is created (with the new capacity) and the old array is copied into a new one. So each time the internal buffer (the
char array) has to be made larger, it has a very, very slight influence on the performance. That's why if you know a StringBuilder will hold at least 100 characters,
you should create a StringBuilder with an initial capacity of 100 instead of using the default initial capacity. It will improve performance (because you have fewer "internal buffer made larger" operations).
What do you need to know for the exam about the capacity?
This post to the rescue!
Note: the ArrayList uses a capacity as well (for exactly the same reason). It's also covered in the aforementioned post.
Hope it helps!
Kind regards,
Roel