Strings are immutable - that means I should never use += and only StringBuffer?

前端 未结 11 1441
醉梦人生
醉梦人生 2021-01-04 08:12

Strings are immutable, meaning, once they have been created they cannot be changed.

So, does this mean that it would take more memory if you append things with += th

11条回答
  •  -上瘾入骨i
    2021-01-04 08:54

    I agree with all the answers posted above, but it will help you a little bit to understand more about the way Java is implemented. The JVM uses StringBuffers internally to compile the String + operator (From the StringBuffer Javadoc):

    String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

         x = "a" + 4 + "c"
    

    is compiled to the equivalent of:

         x = new StringBuffer().append("a").append(4).append("c")
                               .toString()
    

    Likewise, x += "some new string" is equivalent to x = x + "some new string". Do you see where I'm going with this?

    If you are doing a lot of String concatenations, using StringBuffer will increase your performance, but if you're only doing a couple of simple String concatenations, the Java compiler will probably optimize it for you, and you won't notice a difference in performance

提交回复
热议问题