Akinn
Akinn

Reputation: 2078

Speed up hashmap writes

I have a Hashmap composed of a fixed number of keys which is preventively populated. Now, in a loop I have to check each key to replace the value in case it must be changed.

Sadly, it is pretty slow due to the number of iterations required. I really would like to maintain a key-value structure because it is used on the top and at the end of my module but I would like to improve the performance at least.

I also thought to an arrayList in order to improve insertion time, but in that case the search would be slower and I'd lose the key-value feature. What if I sort the arraylist on the key at the beginning and then look for values with a binary search?

Is there a better solution to search and write on a map?

Thanks,

EDIT: Code

  for (Entry<String, VariableInfo> entry : VariablesMap.entrySet()){

  String varName = entry.getKey();
  VariableInfo info = entry.getValue();

  Object value = info.convertToValue();

        DialogWait dialogWindow = new DialogWait();                     
        SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {

                while(newTimeSet != _record.getCurrentTimeMs()) {

                    _record.stepForward();

                    if(valuesMap.get(varName)!=value)
                        valuesMap.put(varName, value);
                }
                dialogWindow.close();
                return null;
            }
        };

        swingWorker.execute();          
        dialogWindow.makeWait("Loading");                   
}

Upvotes: 1

Views: 77

Answers (1)

TreffnonX
TreffnonX

Reputation: 2930

Now, in a loop I have to check each key to replace the value in case it must be changed.

Is there maybe a way to update the list, if the condition that the value must change becomes true? So basically, can you rewrite code outside the map, to react to the change, rather than the map changing periodically, depending on the state? This is usually a pretty strong improvement on performance, and will make your map way more useful, as it is much more up to date.

If you truly must check every entry in the Map periodically, then you have a runtime of O(n) by using map.entrySet() and iterating over it. It cannot be optimized, assuming that you cannot predict information about the mappings entered.

If you have certain entries, that change with a higher frequency or probability, you could optimize by applying a higher check-frequency there, than for the rest. For that, you could use a LinkedHashMap. With it, you can insert elements, and the list keeps track of the order of insertion. With it, you could easiely remember the last n changed elements, and prioritize them, over others.

Upvotes: 1

Related Questions