是否StringBuilder.toString保留内置字符串? [英] Does StringBuilder.toString retain the built string?

查看:127
本文介绍了是否StringBuilder.toString保留内置字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个StringBuilder收集的字符串,我会定期刷新到服务器。如果刷新失败,我想保持琴弦下次再试试,虽然在平均时间我可能会得到额外的字符串要发送的必须添加到StringBuilder。

I'm creating a StringBuilder to collect strings that I periodically flush to a server. If the flush fails, I want to keep the strings to try again next time, although in the mean time I might get additional strings to send which must be added to the StringBuilder.

我想知道什么是最有效的方法,这样做会是这样,因为这是一个Android应用程序,其中电池的使用,因此CPU占用率是一个大问题正在做。并调用的StringBuilder的toString()函数店得到的字符串在内部返回,以便后续调用不必做过度复制所有原始字符串的工作?或者,如果调用失败,我应该创建的toString与返回值初始化的新的StringBuilder()?

What I want to know is what the most efficient way to do this would be, as this is being done in an Android app where battery usage and thus CPU usage is a big concern. Does calling StringBuilder's toString() function store the resulting string it returns internally so that a subsequent call doesn't have to do the work of copying all the original strings over? Or if the call fails, should I create a new StringBuilder initialized with the return value from toString()?

推荐答案

下面是<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuilder.java\"相对=nofollow> OpenJDK源码code为的StringBuilder

public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}

的<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String\"相对=nofollow>来源与这些参数的字符串构造是:

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);
}

所以,是的,它并创建一个新的字符串每次,是的,它使的char [] 每次

注意,这是一个实现的toString ,另有实现可能显着不同是很重要的。

It's important to note that this is one implementation of toString, and another implementation may obviously be different.

这篇关于是否StringBuilder.toString保留内置字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆