The project that I am currently working on has an interesting issue. We just started using a tool called YourKit Java Profiler, and it shows that we have 26 MB of duplicate copies of the empty string "". My first reaction was shock: I thought all compilers were smart enough to recognize that immutable strings (such as string constants) that are identical should reference a single version of that string. But if YourKit Java Profiler is to be believed, that is NOT happening. I asked the question
here, and the answers that I received indicated that Java does create only a single version of a string constant -- but that the problem might be:
String str = i + ""
which is a very common Java construct for converting an integer to a string, is turning into something like:
String str = new StringBuilder("").append(i).toString();
The implication is that the new StringBuilder("") is producing a distinct object each time, because that is a mutable string. The solution is to use the somewhat less easy
String.valueOf(i)
to produce the string version of i instead. Does this seem like a plausible explanation of how we end up with 26 MB of "" copies?
Tidak ada komentar:
Posting Komentar