[Solved] Fixed Array?/ StringBuilder?/ String? which is best way to create a string, if 84 strings to be appended


If by “best” you mean “most memory and/or runtime efficient” then you’re probably best off with a StringBuilder you pre-allocate. (Having looked at the implementation of String.join in the JDK, it uses StringJoiner, which uses a StringBuilder with the default initial capacity [16 chars] with no attempt to avoid reallocation and copying.)

You’d sum up the lengths of your 84 strings, add in the number of commas, create a StringBuilder with that length, add them all, and call toString on it. E.g.:

int length = 0;
for (int i = 0; i < strings.length; ++i) {
    length += strings[i].length();
}
length += strings.length - 1; // For the commas
StringBuilder sb = new StringBuilder(length);
sb.append(strings[0]);
for (int i = 1; i < strings.length; ++i) {
    sb.append(',');
    sb.append(strings[i]);
}
String result = sb.toString();

2

solved Fixed Array?/ StringBuilder?/ String? which is best way to create a string, if 84 strings to be appended