问题描述
我事先知道,将有84个字符串要用逗号分隔符追加,然后创建一个字符串,
I know in advance that, there would be 84 strings going to be appended by comma separator, to create one string then,
哪种方法最好是固定的数组,字符串还是字符串生成器?
Which way is be better a fixed Array, Strings or String Builder?
推荐答案
如果用最佳表示内存和/或运行时效率最高,那么您最好使用预先分配的 StringBuilder
。 (在JDK中研究了 String.join
的实现,它使用了 StringJoiner
,后者使用了 StringBuilder
,其默认初始容量为[16个字符],并且不尝试避免重新分配和复制。)
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.)
您总结了一下84个字符串的长度,添加逗号数,创建具有该长度的 StringBuilder
,全部添加,然后调用 toString
就可以了。例如:
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();
这篇关于固定数组?/ StringBuilder?/字符串?如果要追加84个字符串,这是创建字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!