|
|
|
|
|
by gf000
89 days ago
|
|
> For example, appending to a string in a loop. That only happens because of how Java handles strings. In C++, that's very fast. As fast as it can get, really. Since it all goes into the same buffer that gets mutated and expands at a good growth rate Well everything comes at a price. Just imagine how many billions of very hard to debug bugs did Java save the world from by going immutable on Strings, at the expense of some slow down when used without a though, and pretty much every java book starts with how to avoid it since decades? |
|
The same thing is true for C++. Value semantics have a cost. In C++, passing a string to a function is very expensive because it calls a copy constructor, so you have to remember to use a reference to avoid that. In Java, that's basically free because of reference semantics.
I also want to say that, while Java has immutable strings, that is a bit undone by the reference semantics of the language. C++ has mutable strings but value semantics, which means that passing a string to a function is safe. It won't be mutated, even though strings are mutable like most C++ containers. In Java, passing containers around is generally not safe, and you can't assume they won't be mutated.