Title: RE: [jdjlist] RE: Slow: string += string

Dear David,

> Actually given your example, using string literals, it's more efficient to
> write:

>   String myString = "Something" + "Something Else";

> because the compiler doesn't need to concatenate these at runtime.

In this case it's true, since you're only adding 2 String objects -- the example was necessarily brief for clarity.

> In other words, this:

>   String myString = "SELECT " + columnlist + " FROM " + tablename + "
> WHERE " + keyname " = " + key;

> and this:

>   StringBuffer sb = new StringBuffer("SELECT ");
>   sb.append(columnlist);
>   sb.append(" FROM ")'
>   sb.append(tablename);
>   sb.append(" WHERE ");
>   sb.append(keyname + " = " + key);
>   String myString = sb.toString();

> are both equivalent to:

<snip>

Actually, if you read the StringBuffer API carefully, you'll note that the compiler "has the option" to optimize String object concatenation.  Actually, as the author of the original post (and my own studies) indicated, what most compilers (most unfortunately) do is concatenate only 2 strings at a time. Thus the overwhelming time/system resources needed to append lots of String objects in a loop.

So this:

String myString = "SELECT " + columnlist + " FROM " + tablename + "
WHERE " + keyname " = " + key;

Depending on the JVM, actually translates to:

String temp1 = new StringBuffer().append("SELECT ").append(columnlist).toString();
String temp2 = new StringBuffer().append(temp1).append(" FROM ").toString();
String temp3 = new StringBuffer().append(temp2).append(tablename).toString();
.
.
.
etc.

It is the creation/destruction of the multitude of extraneous tempN objects that bogs down the JVM, and that is exactly what we're trying to avoid by using StringBuffer explicitly.

So + (for greater then 2 String objects) and .append() are unfortunately not equivalent.


However, I wholeheartedly agree that:

   String myString = new StringBuffer("SELECT ")
        .append(columnlist)
        .append(" FROM ")
        .append(tablename)
        .append(" WHERE ")
        .append(keyname)
        .append(" = ")
        .append(key).toString();

is equivalent to using explicitly defined StringBuffer() object -- I said that much in my earlier email, it's just (IMHO) a more elegant shortcut that few programmers use.

> Choosing between them is mostly a matter of style, unless the logic demands
> that you use multiple expressions.

Ditto.

Greg

____________________________________________________
To change your JDJList options, please visit:
http://www.sys-con.com/java/list.cfm

Be respectful! Clean up your posts before replying
____________________________________________________

Reply via email to