Does StringBuilder.toString keep an inline string?

I create a StringBuilder to collect strings that I periodically do on the server. If the flash fails, I want the lines to try again next time, although at the same time I could get extra lines to send that should be added to StringBuilder.

What I want to know is the most efficient way to do this, as it is done in an Android app, where battery usage and therefore CPU usage are a big problem. Does the StringBuilder toString () function call the resulting string that is returned internally, so that a subsequent call does not need to do the job of copying all the source strings? Or if the call failed, should I create a new StringBuilder initialized with a return value fromStString ()?

+4
source share
3 answers

Here is the OpenJDK source code for StringBuilder :

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

The source for the String constructor with these parameters:

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

So yes, it creates a new String every time, and yes, it makes a copy of char[] every time.

It is important to note that this is one implementation of toString , and the other implementation may be different.

+4
source

This will be an implementation detail. Since java strings are immutable, the correct impl can choose to share or create new strings from StringBuilder.toString (), even if it is not required.

As everyone says, you can check if this is really a performance issue for you. If this is one (awkward) workaround, then wrap StringBuilder and cache the resulting string. You can use the dirty flag to indicate that the content has been modified.

0
source

The StringBuilder.toString API says that the new String object is allocated and initialized to contain the character sequence currently represented by this object.

0
source

All Articles