String concat speed in Java

I'm rapidly prototyping the SQL query instead of doing it in the right way. I just decided to attack it with a bunch of string connections. I thought it would be very slow all the time, but it doesn't matter because I just test the query To my surprise, Java says this code takes 0 milliseconds to complete? Does it take more time than StringBuilder or something like that?

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, it's very ugly, but the problem is not whether it predicts SQL, but why it's so fast

Build time: 0 ms

Editor: I ran 10000 tests in 20 terms, which took about 10 seconds, so it was about 1 / 10 millisecond Now let me think about it. Obviously, unless I start getting long strings, there won't be much calculation

Solution

You only make 29 connections - I hope it's less than a millisecond

If you want to test this code against the StringBuilder implementation, you should iterate it about 10000 times (and warm up the JVM appropriately)

benchmark

I'd like to know the exact difference in this case, so I convert your code to use Concat () and StringBuilder are benchmarked with 10000 iterations (2000 warm ups), including 5 fields and 20 terms, all of which randomly generate 32 char strings

Results (in milliseconds):

plus: 19656 (0.5/ms)
 concat: 5656  (1.77/ms)
builder: 578   (17.3/ms)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>