String concatenation in a for loop. Java 9

前端 未结 3 1730
离开以前
离开以前 2020-12-17 16:56

Please correct me if i\'m wrong. In Java 8, for performance reasons, when concatenating several strings by the \"+\" operator StringBuffer was invoked. And the problem of cr

3条回答
  •  情深已故
    2020-12-17 17:35

    Your loop is creating a new String each time. StringBuilder (not StringBuffer, which is synchronized and should not be used,) avoids instantiating a new object each time.

    Java 9 may be adding new features, but I would be surprised if things have changed. This issue is much older than Java 8.

    Addition:

    Java 9 has modified the way String concatenation is performed when using the "+" operator in a single statement. Up to Java 8, it used a builder. Now, it uses a more efficient approach. However, that does not address using "+=" in a loop.

提交回复
热议问题