Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Jan Burse Newsgroups: comp.lang.java.programmer Subject: Re: StringBuilder Date: Mon, 05 Sep 2011 05:27:15 +0200 Organization: albasani.net Lines: 51 Message-ID: References: <96f358c8-a024-40db-b60b-300186c2f813@o10g2000vby.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net dBq0oZaNM3MEkMdAtteHjiLq6o2OBemYWdeGz2BVO6DnM3E9cW23WLymSLjiniCPl0db5iXzL3biD26HWkVwIQ== NNTP-Posting-Date: Mon, 5 Sep 2011 03:27:16 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="qpnmB3qi8LZBDeOrDEOEvqcV0blnfF3gdojJPhOGX3i6h3yhq6v/nwftbUTBbhsYD8DE6EGMW7QmAjWGL0TbQQiRM/GavesiO3RP3HKoUHAlxpNGlpWpMzSkcJJix3FP"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:6.0.1) Gecko/20110830 Firefox/6.0.1 SeaMonkey/2.3.1 In-Reply-To: <96f358c8-a024-40db-b60b-300186c2f813@o10g2000vby.googlegroups.com> Cancel-Lock: sha1:1uiYzwV0NflSsDvRRfWH1C2YWIE= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7569 bob schrieb: > Is there any way to use StringBuilder but with + signs instead of > append? The + in Java does already internally use StringBuilder. There is only an issue when you want to accumulate a string value. If you then explicitly use StringBuilder you are faster, because you save the new StringBuilder() and toString(). So this is faster, since it uses 1 new and 1 toString(): StringBuilder buf=new StringBuilder(); for (int i=0; i<100; i++) { buf.append(i); buf("*"); buf.append(i); buf.append("="); buf.append((i*i)); buf.append("\n"); } System.out.println(buf.toString()); Whereby this code is slower: String res=""; for (int i=0; i<100; i++) { res+=i+"*"+i+"="+(i*i)+"\n"; } System.out.println(res); It is translated to the following code by the compiler, and thus uses 100 new and 100 toString(): String res=""; for (int i=0; i<100; i++) { StringBuilder _buf=new StringBuilder(res); _buf.append(i); _buf("*"); _buf.append(i); _buf.append("="); _buf.append((i*i)); _buf.append("\n"); res=_buf.toString(); } System.out.println(res); For more information see for example here: http://caprazzi.net/posts/java-bytecode-string-concatenation-and-stringbuilder/ Best Regards