StringBuffer is obsolete?

后端 未结 5 1491
梦毁少年i
梦毁少年i 2021-02-03 17:16

In the book \"Effective Java\", Josh Bloch says that

StringBuffer is largely obsolete and should be replaced by the non-synchronized implementation \'S

5条回答
  •  迷失自我
    2021-02-03 17:51

    It's obsolete in that new code on Java 1.5 should generally use StringBuilder - it's very rare that you really need to build strings in a thread-safe manner, so why pay the synchronization cost?

    I suspect code that you see using StringBuffer mostly falls into buckets of:

    • Written before Java 1.5
    • Written to maintain compatibility with older JDKs
    • Written by people who don't know about StringBuilder
    • Autogenerated by tools which don't know about StringBuilder

提交回复
热议问题