Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you run with <code>-XX:-UseTLAB</code></p> <pre><code>public static void main(String... args) throws Exception { StringBuilder text = new StringBuilder(); text.append(new char[1024]); long free1 = free(); String str = text.toString(); long free2 = free(); String [] array = { str.substring(0, 100), str.substring(101, 200) }; long free3 = free(); if (free3 == free2) System.err.println("You must use -XX:-UseTLAB"); System.out.println("To create String with 1024 chars "+(free1-free2)+" bytes\nand to create an array with two sub-string was "+(free2-free3)); } private static long free() { return Runtime.getRuntime().freeMemory(); } </code></pre> <p>prints</p> <pre><code>To create String with 1024 chars 2096 bytes and to create an array with two sub-string was 88 </code></pre> <p>You can see its consuming more memory that you might expect if they shared the same back end store.</p> <p>If you look at the code in the <strong>String</strong> class.</p> <pre><code>public String substring(int start, int end) { // checks. return ((beginIndex == 0) &amp;&amp; (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); } String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } </code></pre> <p>You can see that substring for <strong>String</strong> doesn't take a copy of the underlying value array.</p> <hr> <p>Another thing to consider is the <a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html" rel="nofollow"><code>-XX:+UseCompressedStrings</code></a> which is on by default on newer versions of the JVM. This encourages the JVM to use byte[] instead of char[] where possible.</p> <p>The size of the headers for the String and array object varies for 32-bit JVMs, 64-bit JVM with 32-bit references and 64-bit JVMs with 64-bit references.</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