StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2199
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  粉色の甜心
    2020-11-21 04:54

    In Java 9 the version 1 should be faster because it is converted to invokedynamic call. More details can be found in JEP-280:

    The idea is to replace the entire StringBuilder append dance with a simple invokedynamic call to java.lang.invoke.StringConcatFactory, that will accept the values in the need of concatenation.

提交回复
热议问题