I have a ResultSet with list of Stock exchanges and Countries, in which they reside. Nonetheless, in my database, not every Cxchange has an country_id, therefore when creating Exchange objects, bunch of them has country_id and country_title null values. Due to the memory optimization, I planned to intern all duplicate Strings (countries, currencies, etc.), but noticed, that I get a NullPointerException, which is loggical. Is there some workaround, how to avoid duplicate strings with intern and also don't get a NPE? Thank you.
-
1You could check if it's null before you intern it – khelwood Jan 28 '20 at 19:46
-
1just gonna share [one of many](https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize) links about premature optimization ;) – Kaan Jan 28 '20 at 19:54
-
`intern` is more a historical feature. Once used for XML for instance, but costly in the perm space. See https://stackoverflow.com/a/59070703/984823 – Joop Eggen Jan 28 '20 at 20:14
2 Answers
Some options are:
Given there are less than 200 countries, and less than that many exchanges (there are only 60 major exchanges globally), it would be trivial to provide the missing data to your exchanges.
Provide a default value programatically, either in java or via your query, eg assign 0
to the country_id
and ""
to country_title when they are null
in the database.
Don't bother interning - with so few Strings, such a micro optimisation would have no measurable effect.

- 412,405
- 93
- 575
- 722
Thank you guys, there are much more strings used in the app, countries and exchanges were just an example. Totally there are around 500k Strings, out of which 50k are unique, i.e. around 30mb wasted. Not a big deal indeed.
After some research, I will not intern strings, given that the app should run on a well equiped PCs :)

- 1