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

前端 未结 11 1445
醉梦人生
醉梦人生 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:01

    In Java 5 or later, StringBuffer is thread safe, and so has some overhead that you shouldn't pay for unless you need it. StringBuilder has the same API but is not thread safe (i.e. you should only use it internal to a single thread).

    Yes, if you are building up large strings, it is more efficient to use StringBuilder. It is probably not worth it to pass StringBuilder or StringBuffer around as part of your API. This is too confusing.

提交回复
热议问题