Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: StringBuilder Date: Sun, 18 Sep 2011 08:15:00 -0400 Organization: A noiseless patient Spider Lines: 39 Message-ID: References: <96f358c8-a024-40db-b60b-300186c2f813@o10g2000vby.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 18 Sep 2011 12:15:06 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="f8igmItKsWs6nM5YanFxAA"; logging-data="30228"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Qb5BQS2p8HOE4gbN6tPd1" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20110902 Thunderbird/6.0.2 In-Reply-To: Cancel-Lock: sha1:kUOp1xNZOk0guXdWUkj1GsJFb4Q= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:8124 On 9/18/2011 1:44 AM, Peter Duniho wrote: (Amusing aside: Thunderbird's spell-checker wants to change Peter's last name to "Whodunit.") > On 9/17/11 3:34 PM, Roedy Green wrote: >> [...] >> StringBuilder composes its string in a char[]. Unfortunately it can't >> simply plop that into a String object at the end. It has to allocate >> yet another buffer, copy into it, and that becomes your string object. >> [...] > > Are you sure that's the implementation? > > In .NET, there is also a String and StringBuilder class pair, and > StringBuilder.ToString() does in fact just create a new String instance > using the existing buffer.[...] > > In any case, if Java does _not_ implement it that way, I suspect that's > out of a different decision-making process rather than ignorance. In > other words, they have already considered whether it's a worthwhile > optimization and decided otherwise. [...] I don't have old Java source, but I do have an old O'Reilly book ("Java In a Nutshell, 2nd Edition, Covers Java 1.1, by David Flanagan") that states The StringBuffer.toString() method does not copy the internal array of characters; instead it shares that array with the new String object, and makes a new copy for itself only when further modifications are made to the StringBuffer object. Assuming the author was correct, it follows that the implementation changed at some later point. Presumably, that change was driven by evidence that the "optimization" wasn't worth while. -- Eric Sosman esosman@ieee-dot-org.invalid