Why is StringBuilder faster than String?

Because String uses + to concatenate strings, a new object is created each time, a new String.

StringBuilder concatenates strings with the append() method without creating new objects.

So, why slow? Because object creation is slow. Why is object creation slow? Because creating objects involves allocating memory and so on. If you just create a couple of objects, that’s fine, because there’s basically no difference. If you create tens of thousands of objects, it starts to matter.

StringBuilder has only one object from start to finish. No new objects are created, but memory is allocated. When is memory allocated? When the StringBuilder is running out of memory, it checks that it is running out of memory, and then automatically expands it – but not every time it has been added to the StringBuilder, because it may have been added to the StringBuilder many times, but it still has enough memory, so it doesn’t need to expand it until it runs out of memory again.

Source code analysis

String

String concatenation creates new objects. Why? Because String data is constant, it cannot be changed.

Since the data of the original string object cannot be changed, what if you want to concatenate it into a new string? Only new objects can be created.

StringBuilder

reference

zhuanlan.zhihu.com/p/65628607

www.bilibili.com/read/cv1226…

www.javashuo.com/article/p-k…

Juejin. Cn/post / 684490…

www.cnblogs.com/xiaofuge/p/…