0

When I migrated my jdk from jdk_8u261 to jdk11.0.11, the performance of String concat speed has dropped dramatically. For example, with the following code, jdk_8u261 spends about 1ms , jdk11.0.11 spends about 500ms. I realize that jdk11 make some optimization with String concatenation, such as StringConcatFactory and some concatenation strategy. I don't see why it is worser than jdk8 in my case. Here is the demo:

    // alphabet concat test
    String a = "a";String b = "b";String c = "c";String d = "d";String e = "e";
    String f = "f";String g = "g";String h = "h";String i = "i";String j = "j";
    String k = "k";String l = "l";String m = "m";String n = "n";String o = "o";
    String p = "p";String q = "q";String r = "r";String s = "s";String t = "t";
    String u = "u";String v = "v";String w = "w";String x = "x";String y = "y";
    String z = "z";


    long t1 = System.currentTimeMillis();
    String str1 = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p
                    + q + r + s + t + u + v + w + x + y + z;
    System.out.println(System.currentTimeMillis() - t1);
JasonYu
  • 61
  • 3
  • 7
    `currentTimeMillis` isn't an accurate measure of execution time. Use better tools to measure performance, please. – Sweeper Jun 01 '21 at 07:52
  • Have you tried to use an String Builder? With String + String + ... Java generate after each string a new object leading to worse performance. – Marlon Jun 01 '21 at 09:08
  • @Marlon Thanks for your suggestion, I believe nobody would use this demo in real code. The point of this demo is to show that the same code perform worse in jdk11 which is strange that jdk11 has more optimzation theoretically about String concatenation than jdk8. I just wanna figure out the reason. – JasonYu Jun 01 '21 at 09:23
  • @Sweeper Thanks. First of all, the time costs are the avarage value of 10 executions, the result is not occasional. Secondly, despite the currentTimeMillis() is not very accurate , the gap between time costs is huge enough(for about 500:1), which can not simply be interpreted as tools problem. I believe that change to other tools, the result will not change a lot. – JasonYu Jun 01 '21 at 09:35
  • 1
    Recommended reading: https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Sweeper Jun 01 '21 at 09:38
  • @Sweeper Roger that, appreciate. – JasonYu Jun 01 '21 at 10:14
  • 1
    The first time use of `StringConcatFactory` has the same issues as the first time use of `LambdaMetaFactory` which are described in [this answer](https://stackoverflow.com/a/34642063/2711488). Things change when you perform multiple string concatenations in one runtime or even evaluate the same expression multiple times. – Holger Jun 02 '21 at 11:12

0 Answers0