Home  >  Q&A  >  body text

java - StringBuffer转成String,可以不同过tostring,而是通过+“”的方式转换吗?

PHP中文网PHP中文网2716 days ago644

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:48:23

    sb is essentially a StringBuffer object. Directly sb+"" is calling sb.toString() to splice it with "". In addition, StringBuffer is thread-safe. Why use StringBuilder or StringBuffer? The reason is that the String class in Jdk is of final type, but why can the final modified version exist in the form of String str = s + "";? Because in jvm, every time + is executed, a temporary String object will be created, and then the String str = a + b; you see; is actually String str = new String(a) + new String(b); In this way, if there are too many strings to be spliced, many String objects will be created. Therefore, the overhead of gc will increase. Therefore, such frequent operations do not directly use string splicing, but use StringBuilder or StringBuffer. replace.

    reply
    0
  • Cancelreply