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

前端 未结 11 1527
醉梦人生
醉梦人生 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 08:49

    You're right that Strings are immutable, so if you're trying to conserve memory while doing a lot of string concatenation, you should use StringBuilder rather than +=.

    However, you may not mind. Programs are written for their human readers, so you can go with clarity. If it's important that you optimize, you should profile first. Unless your program is very heavily weighted toward string activity, there will probably be other bottlenecks.

提交回复
热议问题