Kayaman wrote:I see your point here. So indirectly you suggest to use StringBuilder instead of string. But when I need to compare the text with other literal strings, it would again require to be converted to a string. What I think is, won't it be better to take char arrays and use standard stringCompare functions to do a char-by-char comparison? In short, what JVM does for me in case of strings, I would do it myself, but at the cost of a mutable structure.
If you're doing a lot of character twiddling, you might want to use StringBuilders instead of Strings.
Kayaman wrote:Actually my RAM is limited to 1 GB and my application is consuming 690 MB of memory. That's what bothers me. In that case, I may have to run the Garbage collector myself.
Even if JProfiler shows you have thousands of Strings, you probably shouldn't worry about it unless they're not being reclaimed and you're running out of memory.
gimbal2 wrote:Thats the exact problem, where I cannot use JProfiler to see the precise location where these strings are created. As of now, it shows me the application's memory snapshot where strings are counting in thousands.
I wouldn't worry about that too much unless your profiler can show you a spot where these string manipulations are creating a dent in performance.
I have a java application which in Jprofiler shows tens of thousands of strings created.That is entirely normal. Last time I did an exercise like that I found the two most populous classes were String and AWTEventMulticaster (it was a GUI program), by a considerable margin.
BIJ001 wrote:Yes. But string is immutable, whereas char array is mutable.
A zero-sized char array also takes some place.
By end of Code-1, 80 bytes of memory is blocked, out of which 40 bytes (of first initialization of str) would be taken up by garbage collector in its next cleanup cycle.
// Code-1 String str = null; str = ""; .... str = ""; // Code-2 char arrChar = new char; arrChar = '\0'; .... arrChar = '\0';
Yes. But string is immutable, whereas char array is mutable.So?
String str = null;Takes just the space for the reference.
str = "";Points the reference into the constant pool entry for "".
str = "";Points the reference into the constant pool entry for "". Again.
char arrChar = new char;Takes up space for the reference and space for the array.
arrChar = '\0';Has no effect on memory usage.
arrChar = '\0';Has no effect on memory usage, again.
By end of Code-1, 80 bytes of memory is blockedNo.
out of which 40 bytes (of first initialization of str) would be taken up by garbage collector in its next cleanup cycle.No. All the memory concerned apart from the reference itself is in the constant pool for the class, put there by the compiler, once per unique literal in the source text of the class. There is only one unique literal there and it is zero length. None of it is garbage-collectable.