Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Note: This answer uses examples that might not be relevant in modern runtime JVM libraries. In particular, the <code>substring</code> example is no longer an issue in OpenJDK/Oracle 7+.</strong></p> <p>I know it goes against what people often tell you, but sometimes explicitly creating new <code>String</code> instances <em>can</em> be a significant way to reduce your memory.</p> <p>Because Strings are immutable, several methods leverage that fact and share the backing character array to save memory. However, occasionally this can actually increase the memory by preventing garbage collection of unused parts of those arrays.</p> <p>For example, assume you were parsing the message IDs of a log file to extract warning IDs. Your code would look something like this:</p> <pre><code>//Format: //ID: [WARNING|ERROR|DEBUG] Message... String testLine = "5AB729: WARNING Some really really really long message"; Matcher matcher = Pattern.compile("([A-Z0-9]*): WARNING.*").matcher(testLine); if ( matcher.matches() ) { String id = matcher.group(1); //...do something with id... } </code></pre> <p>But look at the data actually being stored:</p> <pre><code> //... String id = matcher.group(1); Field valueField = String.class.getDeclaredField("value"); valueField.setAccessible(true); char[] data = ((char[])valueField.get(id)); System.out.println("Actual data stored for string \"" + id + "\": " + Arrays.toString(data) ); </code></pre> <p>It's the whole test line, because the matcher just wraps a new String instance around the same character data. Compare the results when you replace <code>String id = matcher.group(1);</code> with <code>String id = new String(matcher.group(1));</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload