Hi there,
I'm still not 100% sure about why I would choose to use StringBuffer or StringBuilder classes rather than Strings.
At first I thought it was because all
String objects are referenced from the String Constant Pool and so a lot of memory would be used up if you had lots of String manipulation to do. But after reading
this article on Strings and String literals I understand that it is only String Literals that are referenced from the String Constant Pool and that this is all done at compile time, whereas if a string is created at runtime and the reference to it is lost, then it will be eligible for Garbage Collection just like any other object.
So is it just that if you did loads of String manipulation work then there would be so many discarded objects that memory would be used up and
Garbage Collection would be forced to run?
I'm also a bit confused by a paragraph in K&B
SCJP 6 that says:
String objects are immutable, so if you chose to do a lot of manipulations with String objects, you will end up with a lot of abandoned String objects in the String pool. (Even in these days of gigabytes of RAM, it's not a good idea to waste precious memory on discarded String pool objects) One the other hand, objects of type StringBuffer and StringBuilder can be modified over and over again without leaving behind a great effluenceof discarded String objects.
It is the bit that says "you will end up with a lot of abandoned String objects in the String pool" that is confusing me. I thought that only literals were referenced from the String Pool (or is that different from String Literal Pool?). I read
this post on Garbage Collection for Strings and Joe Ess says that
The literal pool cannot get "full". The compiler creates it by pulling the literals out of your code, so it is a set size when you start your program. It neither grows nor shrinks.
So as i understand it any Strings created at runtime are not referenced from the String Literal Pool, but instead are discarded and eligible for GC if they are abandoned. So the only advantage of using the StringBuilder/Buffer classes is that you save the GC having to clean up memory because the StringBuilder/Buffer objects use the same memory over and over again and you don't end up with so much wasted memory that needs GC to free it. So
it is more efficient to use StringBuilder/Buffer because GC doesn't have to run as often. But, it is *not* true that the String Literal Pool will get bigger and bigger because the String Literal Pool references are all created at compile time.
Grateful for any comments.
Cheers
Joe