Search code examples
javastringbuilder

what are the pros and cons string plus operator and stringbuilder append?


I have hard coded SQL queries which uses string + operator for string concatenation and I'm about to replace String + operator with stringBuilder append , I just need to compare both methods for pros and cons.

Sample code :

   insertStat = CMSCon.prepareStatement("INSERT INTO PROFILE"
                + " (PROFILECODE,DESCR,CTYPE,"
                + " STAT,CR,AMOUNT,PERCENTAGE,COMB,CMETHOD,"
                + " LASTUPDATEDUSER,LASTUPDATEDTIME,CREATEDTIME)"
                + " VALUES (?,?,?,?,?,?,?,?,?,?,SYSDATE,SYSDATE)");

will be replaced by something like this

 StringBuilder sb = new StringBuilder();
        insertStat = CMSCon.prepareStatement(sb.append("INSERT INTO PROFILE")
                .append(" (PROFILECODE,DESCR,CTYPE,")
                .append(" STAT,CR,AMOUNT,PERCENTAGE,COMB,CMETHOD,")
                .append(" LASTUPDATEDUSER,LASTUPDATEDTIME,CREATEDTIME)")
             .append((?,?,?,?,?,?,?,?,?,?,SYSDATE,SYSDATE)").toString());

Solution

  • The compiler turns String+ into calls to a StringBuilder under the covers anyway. So in your example there is no performance difference in the end, because the final byte code should be almost the same (you might want to use javap to check that yourself).

    So, normally, you only use StringBuilder manually when you have to concatenate data in a loop for example (and performance matters).

    Otherwise you lean towards "better readability" of your code, which you most often (not always) achieve using String+.