In this short article, we would like to answer the question: what is the optimal value for
capacity in the constructor?
Naive answer: the same like the amount of the characters will be stored inside.
// hex color StringBuilder builder = new StringBuilder(7); // # character + 3x byte value value from 00 to FF builder.append('#'); builder.append('00'); // R builder.append('00'); // G builder.append('FF'); // B String color = builder.toString();
MySQL JDBC driver example
In MySQL JDBC driver, escaped value characters are added to the builder with capacity equals to:
int capacity = (int)(1.1 * value.length());
The reason why
1.1 coefficient is used, is the typical amount of the characters after escaping, keeping in the mind, we don't want to reserve too much memory if it is not necessary - it is like empirical value.
JDBC source code part (
// ... StringBuilder buf = new StringBuilder((int) (x.length() * 1.1)); // ...
x is not escaped yet value.