>>>>> "Brad" == Brad Giaccio <[EMAIL PROTECTED]> writes:

  >> 2. :line (21,22) If you look at the source of
  >> java.lang.StringBuffer it seems that buf.append( '\\' ).append(
  >> '\"' ); is cheaper than a buf.append( "\\\"" );


  Brad> Regardless of the append implimentation of append, appending a
  Brad> char instead of a string saves you an object creation as well.
  Brad> Since this code will create a new String object for each
  Brad> append.



        Perhaps I am being a little dim here but Im not convinced that
this is the case. The code for the append functions to StringBuffer
(which Ive included below) show, that appending a char, a char array
or a String to a StringBuffer all work by using copying chars from one
array to another (or in the case of the char just adding straight to
the end of the StringBuffer char array). 

        I can see no extra objects being created here with using the
StringBuffer.append( String ) method. Unless you mean the "///" string
literal. This will come from javas internal string cache, and
therefore represents one extra object creation per VM invocation not
per append invocation which is not really worth worrying about, and
for which the code simplicity would make worth while.


from StringBuffer.java

public synchronized StringBuffer append(String str) {
        if (str == null) {
            str = String.valueOf(str);
        }

        int len = str.length();
        int newcount = count + len;
        if (newcount > value.length)
            expandCapacity(newcount);
        str.getChars(0, len, value, count);
        count = newcount;
        return this;
}

public synchronized StringBuffer append(char str[]) {
        int len = str.length;
        int newcount = count + len;
        if (newcount > value.length)
            expandCapacity(newcount);
        System.arraycopy(str, 0, value, count, len);
        count = newcount;
        return this;
}

public synchronized StringBuffer append(char c) {
        int newcount = count + 1;
        if (newcount > value.length)
            expandCapacity(newcount);
        value[count++] = c;
        return this;
} 


from String.java

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {

        [....Array index checking removed...]
        System.arraycopy(value, offset + srcBegin, dst, dstBegin, 
                         srcEnd - srcBegin);
}

Reply via email to