Mic*_*ael 4 java stringbuilder android
我正在创建一个 StringBuilder 来收集我定期刷新到服务器的字符串。如果刷新失败,我想保留这些字符串以便下次再试,但同时我可能会收到额外的字符串,这些字符串必须添加到 StringBuilder。
我想知道最有效的方法是什么,因为这是在 Android 应用程序中完成的,其中电池使用情况和 CPU 使用情况是一个大问题。调用 StringBuilder 的 toString() 函数是否会存储它在内部返回的结果字符串,以便后续调用不必执行复制所有原始字符串的工作?或者,如果调用失败,我是否应该创建一个新的 StringBuilder,并使用 toString() 的返回值进行初始化?
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
Run Code Online (Sandbox Code Playgroud)
带有这些参数的String构造函数的来源是:
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.offset = 0;
this.count = count;
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
Run Code Online (Sandbox Code Playgroud)
所以是的,它String每次都会创建一个新的,是的,它每次都会创建一个副本char[]。
需要注意的是,这是 的一种实现toString,而另一种实现可能明显不同。
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |