Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of constant strings VS StringBuffer

What arguments can You give for the use one or another variant that is better, faster, more correct.

First variant:

StringBuffer sql = new StringBuffer("SELECT DISTINCT f.ID ")
    .append("FROM FIRST_TABLE F ")
        .append("LEFT JOIN SECOND_TABLE s ON f.ID = s.F_ID ")
    .append("WHERE ")
        .append("F.BOOL = 1 ")
        .append("AND S.DATE IS NOT NULL ")
        .append("AND S.CLOSED = 0 ");

Second variant:

String sql = "SELECT DISTINCT f.ID " +
             "FROM FIRST_TABLE F " +
                "LEFT JOIN SECOND_TABLE s ON f.ID = s.F_ID " +
             "WHERE "
                "F.BOOL = 1 " +
                "AND S.DATE IS NOT NULL " +
                "AND S.CLOSED = 0";

*for note: Class String and Class StringBuffer.

like image 527
old Avatar asked Apr 11 '26 04:04

old


1 Answers

The second is better:

  • It's clearer (more of the code has to do with what you want)
  • It's more efficient, as all the concatenation is being done at compile-time

Even if execution-time concatenation was required (e.g. you had a variable in there), the compiled code would use a StringBuilder or StringBuffer where it needed to (depending on the version of Java you're targeting).

Mind you, if you're executing a database query, the efficiency is going to be utterly insignificant.

like image 129
Jon Skeet Avatar answered Apr 18 '26 06:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!