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

前端 未结 11 1531
醉梦人生
醉梦人生 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条回答
  •  情书的邮戳
    2021-01-04 09:00

    Exactly. You should use a StringBuilder though if thread-safety isn't an issue.

    As a side note: There might be several String objects using the same backing char[] - for instance whenever you use substring(), no new char[] will be created which makes using it quite efficient.

    Additionally, compilers may do some optimization for you. For instance if you do

    static final String FOO = "foo";
    static final String BAR = "bar"; 
    
    String getFoobar() {
      return FOO + BAR; // no string concatenation at runtime
    }
    

    I wouldn't be surprised if the compiler would use StringBuilder internally to optimize String concatenation where possible - if not already maybe in the future.

提交回复
热议问题