String vs. StringBuilder

2018-12-31 08:24发布

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference between the two?

The program I’m working on has a lot of case driven string appends (500+). Is using StringBuilder a better choice?

25条回答
大哥的爱人
2楼-- · 2018-12-31 08:52

StringBuilder is probably preferable. The reason is that it allocates more space than currently needed (you set the number of characters) to leave room for future appends. Then those future appends that fit in the current buffer don't require any memory allocation or garbage collection, which can be expensive. In general, I use StringBuilder for complex string concatentation or multiple formatting, then convert to a normal String when the data is complete, and I want an immutable object again.

查看更多
登录 后发表回答