dsp_099 dsp_099 -4 years ago 99
Ruby Question

Is there a performance difference between `select` and `select!` when called on a Ruby hash?

hash = { 'mark' => 1, 'jane' => 1, 'peter' => 35 }.select {|k,v| v > 1}
#=> { 'peter' => 35 }

What if I have millions of keys - is there a difference between

hash = hash.select

Answer Source

select! will perform better (I'll show the source for MRI, but it should be the same for the others).

The reason for this is that select needs to create a whole new Hash object, and will, for each entry in the hash, copy the entry - if the block succeeds.

On the other hand, select!, will, for each key, remove the value - if the block doesn't succeed - in-place (with no need for new object creation).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download