Reputation: 421
So I do know that java Strings are immutable. There are a bunch of methods that replace characters in a string in java. So every time these methods are called, would it involve creation of a brand new String, therefore increasing the space complexity, or would replacement be done in the original String itself. I'm a little confused on this concept as to whether each of these replace statements in my code would be generating new Strings each time, and thus consuming more memory?
Upvotes: 6
Views: 5303
Reputation: 16476
JDK misses mutating operations for character sequences, i.e. StringBuilder
for some reason does not implement replacement functionality.
A possible option would be to use third party libraries, i.e. a MutableString
. It is available in Maven Central.
Upvotes: 0
Reputation: 2122
They generate new ones each time; that is the corollary to being immutable.
It's true, in some sense, that it increases the 'space complexity', in that it uses more memory than the most efficient possible algorithms for replacement, but it's not as bad as it sounds; the transient objects created during the replaceAll operation and others like it are garbage collected very quickly; java is very efficient at garbage collecting transient objects. See http://www.infoq.com/articles/Java_Garbage_Collection_Distilled for an interesting writeup on some garbage collection basics.
Upvotes: 1
Reputation: 30865
Yes. You have noted it correctly. That immutability of String type has some consequences.
That is why the designers of Java have bring another type that should be used when you perform operations with char sequences.
A class called StringBuilder, should be used when you perform lot of operations that involve characters manipulations like replace. Off course it it more robust and requires more attention to details but that is all when you care about the performance.
So the immutability of String type do not increase memory usage. What increase it is wrong usage of String type.
Upvotes: 1
Reputation: 12484
It is true that it will return a new String , but unless the call is part of some giant loop or recursive function, one need not worry too much.
But if you purposefully wanted to crash your system, I'm sure you can think up some way.
Upvotes: 0
Reputation: 726479
You noted correctly that String
objects in Java are immutable. The only case when replacement, substring, etc. methods do not create a new object is when the replacement is a no-op. For example, if you ask to replace all 'x'
characters in a "Hello, world!"
string, there would be no new String
object created. Similarly, there would be no new object when you call str.substring(0)
, because the entire string is returned. In all other cases, when the return value differs from the original, a new object is created.
Upvotes: 6