Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not use string buffers instead of immutable strings?

More and more compilers make use of immutable strings (because of string interning, but are there other reasons?). However, string buffers are much faster when concatenating strings. Is there any reason why not all compilers use string buffers internally instead of immutable strings?

like image 817
Olle Härstedt Avatar asked May 13 '26 09:05

Olle Härstedt


1 Answers

Probably the biggest argument for immutability is its benefits for concurrency. There's no need to lock and protect an object if you know it will never change. As the cores in our multi-core processors multiply, this benefit becomes more and more compelling.

There are trade-offs, of course. As you mention, string buffers can out-perform the constant allocation of new strings in apps that do a lot of string manipulation. Luckily, most languages include a string buffer tucked away in a library. By default, immutable strings are safer. In some cases, they're faster. If you find they're not working for you, you can always swap in a buffer.

like image 127
Corbin March Avatar answered May 16 '26 11:05

Corbin March