Java - optimal capacity value in StringBuilder

6 points
Created by:

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.


// hex color

StringBuilder builder = new StringBuilder(7);  // # character + 3x byte value value from 00 to FF

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 (com.mysql.cj.ClientPreparedQueryBindings class):

// ...

StringBuilder buf = new StringBuilder((int) (x.length() * 1.1));

// ...

Where: x is not escaped yet value.

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂