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

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

    But the garbage collector will end up freeing the old strings once there are no references to them

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 09:04

    Yes you would and that is exactly why you should use StringBuffer to concatenate alot of Strings.

    Also note that since Java 5 you should also prefer StringBuilder most of the time. It's just some sort of unsynchronized StringBuffer.

    0 讨论(0)
  • 2021-01-04 09:05

    I think it relies on the GC to collect the memory with the abandoned string. So doing += with string builder will be definitely faster if you have a lot of operation on string manipulation. But it's shouldn't a problem for most cases.

    0 讨论(0)
提交回复
热议问题