title: Is there a memory-efficient replacement of java.lang.String?
body: <p>After reading <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip130.html?page=2" rel="noreferrer">this old article</a> measuring the memory consumption of several object types, I was amazed to see how much memory <code>String</code>s use in Java:</p>
  <pre><code>length: 0, {class java.lang.String} size = 40 bytes
  length: 7, {class java.lang.String} size = 56 bytes
  </code></pre>
  <p>While the article has some tips to minimize this, I did not find them entirely satisfying. It seems to be wasteful to use <code>char[]</code> for storing the data. The obvious improvement for most western languages would be to use <code>byte[]</code> and an encoding like UTF-8 instead, as you only need a single byte to store the most frequent characters then instead of two bytes.</p>
  <p>Of course one could use <code>String.getBytes(&quot;UTF-8&quot;)</code> and <code>new String(bytes, &quot;UTF-8&quot;)</code>. Even the overhead of the String instance itself would be gone. But then there you lose very handy methods like <code>equals()</code>, <code>hashCode()</code>, <code>length()</code>, ...</p>
  <p>Sun has a <a href="http://www.freepatentsonline.com/6751790.html" rel="noreferrer">patent</a> on <code>byte[]</code> representation of Strings, as far as I can tell.</p>
  <blockquote>
  <p><strong>Frameworks for efficient representation of string objects in Java programming environments</strong><br />
  ... The techniques can be implemented to create Java string objects as arrays of one-byte characters when it is appropriate ...</p>
  </blockquote>
  <p>But I failed to find an API for that patent.</p>
  <p>Why do I care?<br />
  In most cases I don't. But I worked on applications with huge caches, containing lots of Strings, which would have benefitted from using the memory more efficiently.</p>
  <p>Does anybody know of such an API? Or is there another way to keep your memory footprint for Strings small, even at the cost of CPU performance or uglier API?</p>
  <p>Please don't repeat the suggestions from the above article:</p>
  <ul>
  <li>own variant of <code>String.intern()</code> (possibly with <code>SoftReferences</code>)</li>
  <li>storing a single <code>char[]</code> and exploiting the current <code>String.subString(.)</code> implementation to avoid data copying (nasty)</li>
  </ul>
  <p><strong>Update</strong></p>
  <p>I ran the code from the article on Sun's current JVM (1.6.0_10). It yielded the same results as in 2002.</p>