Tim Crook wrote:
> Hi Giovanni.
>
> I know this is recommended general practice for Strings, but if you are
> using JDK 1.2, wouldn't using HotSpot eliminate the need for hand optimizing
> code like this?
>
HotSpot can make many kinds of code faster, but it's still going to be faster
yet to use a StringBuffer.
The reason for this is that HotSpot still has to obey the rules of the Java
Language Specification, which says that Strings are immutable (i.e. you cannot
change them after they are created). Whenver you ask for a concatenation, a
new String has to be constructed When you say
String value = "abc";
value += "def";
what you are really saying, using an optimized implementation, is in essence:
String value = "abc";
{
StringBuffer temp = new StringBuffer(value);
temp.append("def");
value = temp.toString();
}
Thus, you're creating a new object and doing an object-to-String conversion at
the end, for *every* use of "+=". The same kind of thing happens when you use
the "+" concatenation operator in an expression. If you use the StringBuffer
approach, you only create a StringBuffer once, you only have to incur the
method call for append() for each addition, and you only pay the toString()
price once at the end.
Moral of the story: concatenating strings with a StringBuffer will always be
faster -- enough faster that you should retrain your fingers to code this kind
of thing correctly the first time, every time.
Craig McClanahan
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html