Home > Software design >  System.String is consuming too much heap memory
System.String is consuming too much heap memory

Time:11-28

Consider the below code in any method.

count = new String(text.getBytes()).length()

I am facing memory issue.

I am using this to count number of characters in file. When I am fetching heap dump I am getting huge amount of memory occupied by String Objects. Is it because of this line of code? I am just looking for suggestions.

CodePudding user response:

Assuming text is a String this code is roughly equivalent to count =text.length(). The difference are mostly:

  • it needlessly requires more memory (and CPU time) by basically encoding the code in the platform default encoding and decoding it again
  • if the platform default encoding can't represent any specific characters in text, then those will be replaced with a ?. If those characters aren't in the BMP then this can actually result in a decreased length.

So it's arguably strictly worse than just taking the length() of text (if the second thing is actually intentional, then there's more efficient ways to check for that).

Apart from that, the major problem is probably the size of the content of text: if it's a whole file or some other huge junk of data, then keeping it all in memory instead of processing it as a stream will always produce some memory pressure. You "just" increased it with this code, but the fundamental solution is to not keep the whole thing in memory in the first place (which is possible more often than not).

CodePudding user response:

I think you can get the character count like this

for(int i=0; i<text.length(); i  ) {  
    count  ;
}
  • Related