Optimize memory usage of a collection of Strings in Java

后端 未结 7 1679
有刺的猬
有刺的猬 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:47

    String.intern is the obvious choice as Brian says. But if you don't want to intern across all the String in memory, you can use a Set to first see if the value is present. Here's untested code. You will have to work out removing from reverse map when removing from main

      class Map2 implements Map
      {
        Map _map = Maps.newHashMap();
        Set _rev = Maps.newHashMap();
    
        V put(K k, V v) {
          if (_rev.containsKey(v)) {
            V prev = _rev.get(v);
            return _map.put(k, prev);
          } else {
            _rev.put(v, v);
            return _map.put(k,v);
          }
       }
    

提交回复
热议问题