EN
Java - optimal capacity value in StringBuilder
6 points
In this short article, we would like to answer the question: what is the optimal value for StringBuilder
capacity
in the constructor?
Naive answer: the same like the amount of the characters will be stored inside.
e.g.
xxxxxxxxxx
1
// hex color
2
3
StringBuilder builder = new StringBuilder(7); // # character + 3x byte value value from 00 to FF
4
5
builder.append('#');
6
builder.append('00'); // R
7
builder.append('00'); // G
8
builder.append('FF'); // B
9
10
String color = builder.toString();
In MySQL JDBC driver, escaped value characters are added to the builder with capacity equals to:
xxxxxxxxxx
1
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 (com.mysql.cj.ClientPreparedQueryBindings
class):
xxxxxxxxxx
1
// ...
2
3
StringBuilder buf = new StringBuilder((int) (x.length() * 1.1));
4
5
// ...
Where: x
is not escaped yet value.