Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen is it beneficial to flyweight Strings in Java?
    primarykey
    data
    text
    <p>I understand the <a href="https://stackoverflow.com/questions/2909848">basic idea</a> of java's String interning, but I'm trying to figure out which situations it happens in, and which I would need to do my own flyweighting.</p> <p>Somewhat related:</p> <ul> <li><a href="https://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly">Java Strings: “String s = new String(”silly“);”</a> </li> <li><a href="https://stackoverflow.com/questions/2915511/the-best-alternative-for-string-flyweight-implementation-in-java">The best alternative for String flyweight implementation in Java</a> never quite got answered</li> </ul> <p>Together they tell me that <code>String s = "foo"</code> is good and <code>String s = new String("foo")</code> is bad but there's no mention of any other situations.</p> <p>In particular, if I parse a file (say a csv) that has a lot of repeated values, will Java's string interning cover me or do I need to do something myself? I've gotten conflicting advice about whether or not String interning applies here in my <a href="https://stackoverflow.com/questions/3972127/hashmap-alternatives-for-memory-efficient-data-storage">other question</a></p> <hr> <p>The full answer came in several fragments, so I'll sum up here:</p> <p>By default, java only interns strings that are known at compile-time. <code>String.intern(String)</code> can be used at runtime, but it doesn't perform very well, so it's only appropriate for smaller numbers of <code>String</code>s that you're sure will be repeated <em>a lot</em>. For larger sets of Strings it's Guava to the rescue (see ColinD's answer).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    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