Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any implementation to Remove by Key and get the Value at the same time? [duplicate]

I'm doing a performance critical program (little academic stuff) and I'm looking to optimize wherever possible (not like it proved "this is the" bottleneck).

I have a custom dictionary structure (a wrapper around .NET Dictionary<,>) and I would constantly Remove items at one stage (by the Key value). I need the Value of the removed items. Right now I have to do:

T t;
if !TryGet(key, out t)
   return false;

Remove(key);

That's two lookups. I would love this:

public bool Remove(S key, out T value)
{
    // implementation
}

I know there is nothing in the framework, but is there an implementation somewhere? If so I would change my backing dictionary with that one.

Edit: Hmm I know both TryGetValue and Remove are O(1). Just knowing if there is any collection structure that would give the same effect in just one lookup. As I said I'm trying to optimize as much as possible. Just knowing.

like image 800
nawfal Avatar asked Apr 03 '13 10:04

nawfal


3 Answers

Dictionary<TKey, TValue>.TryGetValue and Dictionary<TKey, TValue>.Remove methods are both O(1) operations, so I don't think you should be concerned about performance here.

like image 186
MarcinJuraszek Avatar answered Oct 19 '22 03:10

MarcinJuraszek


The ConcurrentDictionary has a TryRemove method that does this. It works just like TryGet but it also removes the element.

like image 24
javaNinja Avatar answered Oct 19 '22 02:10

javaNinja


The University of Copenehagen's Generic Collection Library has a Dictionary.Remove() method that appears to do what you want:

bool Remove(K k, out V v)

Returns true if the dictionary contains an entry whose key equals k and if so removes that entry and assigns the associated value to v; otherwise returns false and assigns the default value for T to v.

I've not used this library myself, but I've seen it recommended a few times here on Stack Overflow. It's free to use commercially, subject to this MIT-style license.

like image 6
Matthew Watson Avatar answered Oct 19 '22 03:10

Matthew Watson