Search code examples
javastringconcatenationstringbuffer

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.


Solution

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