Why is StringBuilder.toString() returning new String instances for empty strings ? (original) (raw)

Jan Ohlsen jan.t.ohlsen at gmail.com
Thu Feb 28 12:53:38 UTC 2013


Yes, makes sense to avoid the branching in that method.

Thanks.

On Thu, Feb 28, 2013 at 10:23 AM, Remi Forax <forax at univ-mlv.fr> wrote:

On 02/28/2013 09:07 AM, Volker Simonis wrote:

Probably because the API-Spec (http://docs.oracle.com/javase/7/docs/api/java/lang/ StringBuilder.html#toString%**28%29<http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#toString%28%29> ) says "..A new String object is allocated and initialized to contain the character sequence currently represented by this object..".

Regards, Volker Also, this kind of short circuit 'if' in a heavily used code like StringBuilder.toString() can have bad interaction with the way the VM optimize/deoptimize. See this thread for more information. http://mail.openjdk.java.net/pipermail/core-libs-dev/2012- May/010295.html<http://mail.openjdk.java.net/pipermail/core-libs-dev/2012-May/010295.html> Rémi

On Thu, Feb 28, 2013 at 8:47 AM, Jan Ohlsen <jan.t.ohlsen at gmail.com> wrote: System.out.println( new StringBuilder().toString() == "" ); -> "false"

Any reason for not returning the "" instance? public String toString() { return new String(value, 0, count); } --> public String toString() { return (count > 0) ? new String(value, 0, count) : ""; } ?



More information about the core-libs-dev mailing list