Concatenation speed in Java

I quickly prototyped the SQL query, and instead of doing it right, I just decided to break through it with the put-string, all the while thinking that it would be very slow, but this is not because I was just testing the query. To my surprise, Java says that this code takes 0 ms? Doesn't it take longer with help +, and not StringBuilderor similar?

long t = System.currentTimeMillis();
String load = "";
for (String s : loadFields)
    load += s + ", ";

String sql = "SELECT ";
sql += load + "sum(relevance) AS 'score' " +
        "FROM ( ";

for (int i = 0; i < searchFields.length; i++) {
    sql += "SELECT ";
    sql += load;
    sql += rels[i] + " AS relevance FROM articles WHERE " +
            searchFields[i];

    sql += " LIKE '%" + terms[0] + "%' ";
    for (int z = 1; z < terms.length; z++)
        sql += "AND " + searchFields[i] + " LIKE '%" + terms[z] + "%' ";

    if (i != searchFields.length - 1) sql += " UNION ALL ";
}

sql += ") results GROUP BY " + load.substring(0, load.length() - 2) + " ";
sql += "ORDER BY score desc, date desc";
System.out.println("Build Time: " + (System.currentTimeMillis() - t) + " ms");

Yes, this is very ugly, but it is not about iterpret SQL, but about telling me why it is so fast.

Build Time: 0 ms

Edit: I ran the test 10,000 times with 20 terms and it took about 10 seconds, about 1/10 millisecond. Now that I think about it, it’s pretty obvious that it’s not much to calculate unless I start getting really long strings.

+3
4

29 - , .

StringBuilder, 10 000 ( JVM).

Benchmark

, , .concat() StringBuilder 10 000 (2000 ) 5 20 , 32 char.

( ):

   plus: 19656 (0.5/ms)
 concat: 5656  (1.77/ms)
builder: 578   (17.3/ms)
+9

, , . 100 000 ( ), . , .

+2

.

  • , , . , , . .

  • , . ( , , 20 .)

, , .


, . , ... .

, , GC. ( , StringBuilder, .)

+1

I understand that execution +means that java creates a copy of the original string and every time it adds a new part to the copy. I would have thought it would be slower, but in any case, it would apparently have more memory than StringBuilder. It seems like it would be much more efficient to have StringBuilderwhich you added and only .toStringor String.valueOf()when you finish adding things.

+1
source

All Articles