Optimize memory usage of a collection of Strings in Java

后端 未结 7 1738
有刺的猬
有刺的猬 2021-01-04 21:21

I have a large number of name - value pairs (approx 100k) that I need to store in some sort of cache (say a hash map) where the value is a string with an average of about 30

7条回答
  •  旧巷少年郎
    2021-01-04 21:54

    It somewhat depends upon how you are creating the String.

    One possible way is to use TreeSet that uses a Comparator that can compare existing Strings and the source of your new String. Use SortedSet.tailSet and an Iterator to find an existing String. Or alternatively NavigableSet.ceiling/floor or a TreeMap with a similar setup.

    I wrote a weblog entry about another technique to cache immutable objects (in particular Strings), but that is more suitable for smaller objects.

    String.intern has performance problems.

提交回复
热议问题