Mars
Mars

Reputation: 4995

Remove contents of Hashtable or just instantiate a new Hashtable?

I have an application that responds to being moved.

The listener seems to be invoked many times in one movement, i.e. if I dragged the application from one part of the monitor to another.

I store some data into a Hashtable when this happens. Each time I store data, I need to store into an empty Hashtable.

Would it be better to remove the contents of the Hashtable each time or could I just instantiate a new Hashtable (using the same variable)? The Hashtable will contain no more than 5 key/value pairs.

Would the latter method begin to consume too much memory or would the Java garbage collector free up this memory quick enough?

Upvotes: 3

Views: 90

Answers (1)

faizan
faizan

Reputation: 578

Besides choosing immutable vs mutable Map you need to make a choice between

  • whether you want every change to be immediately visible in the HashMap
  • or you may write the change events to a queue and flush them to HashMap periodically, this would make sure that your HashMap is not written to as frequently as in 1st solution and may give you performance benefits + responsiveness (putting in queue is lighter operation than putting in HashMap).

I would suggest you to go ahead and try both approaches, profile and then find out.

Highest priority must be given to code clarity and understandability. If the performance impact of the clearer method (here using an immutable HashMap) is not unbearable then go for the that.

Upvotes: 1

Related Questions