0

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());
1
  • There's no point in using a StringBuilder unless you're repeatedly appending across multiple statements. Definitely go with + in this case. Commented Apr 3, 2019 at 3:28

1 Answer 1

2

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+.

Sign up to request clarification or add additional context in comments.

2 Comments

is this documented somewhere?
@johnktejik Google is your friend ;-) stackoverflow.com/questions/40267601/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.