I was prototyping an SQL query quickly, and instead of doing it the correct way, I just decided to slam through it with a bunch of string concats, the entire time thinking that this would be extremely slow, but it didn’t matter because I was just testing the query. To my suprise, Java says that this code take 0 ms to complete? Doesn’t it take more time do this with + rather than StringBuilder or 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 the point is not to iterpret the SQL, but to tell me why this is so fast.
Build Time: 0 ms
Edit: I ran the test 10000 times with 20 terms, and it took about 10 seconds, so about 1/10 of a millisecond. Now that I think about it, it is pretty obvious that this isn’t that much to computation unless I start getting really long strings.
You’re only doing 29 concatenations – I should hope that takes less than a millisecond.
If you want to test this code against a StringBuilder implementation, you should iterate it 10,000 times or so (and do proper JVM warm-up).
Benchmark
I was curious to see what the exact difference is in this case, so I converted your code to use
.concat()andStringBuilderand benchmarked with 10,000 iterations (2,000 warmup), with 5 fields and 20 terms, all of them randomly generated 32 char strings.Results (in milliseconds):