How expensive is the "key" function of a Ruby hash? -


i'm using couple of hashes values of hashes key of others.

i need use key couple of times key value can use access in hash.

i wondering kind of performance impact possibly have. in situation, these hashes few in number , contents small, want know theoretically.

should avoid using much? how perform compared getting value key?

think of way: you're doing step value. that's happens time use conditional test , add couple steps computation.

it's obvious there's little overhead associated it, worrying @ point premature optimization. can feel difference, using benchmark class test alternate way of getting hash key, vs. normal way.

i suspect you'll have several million loops see appreciable difference.


here how create reverse mapping mentioned @fontanus:

hash = {a:1, b:2} hash.merge!(hash[hash.values.zip(hash.keys)]) 

which results in:

{     :a => 1,     :b => 2,      1 => :a,      2 => :b } 

it can done coercing hash array, flattening , reversing , turning hash, find less intuitive above. ymmv.

hash.merge!(hash[*hash.to_a.flatten.reverse]) 

@steenslag reminded me of hash.invert. knew there couldn't remember method name:

 >> hash.merge!(hash.invert) {     :a => 1,     :b => 2,      1 => :a,      2 => :b } 

give him upvote that!


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -