Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a memory-efficient replacement of java.lang.String?
    primarykey
    data
    text
    <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("UTF-8")</code> and <code>new String(bytes, "UTF-8")</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>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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