From: Robert Klemme Date: 2008-09-05T00:42:22+09:00 Subject: Re: Hash optimization question 2008/9/4 Roger Pack : >> I guess it will be difficult to get both: fast hash lookup and >> insertion on one hand and fast iteration on the other hand. Is it >> worth the effort? I don't know. This depends on your application. >> Where is this a problem for you? Maybe there is a more efficient data >> structure for your particular problem. > > Yeah I guess it's hard to have the best of both worlds. Hmm. I suppose > that for small hashes which call .each a fix would definitely help, for > large hashes that call .each "a lot" it would probably also be quicker, > and for any hashes which don't call .each it wouldn't be helpful. I > wonder if the slowdown is small enough to make it worth it anyway > [though it would use more RAM too--then again, Ruby isn't known for its > low memory usage] :) The critical issue is not the size of the Has (at least not only) but rather the frequency of change. Personally, since a Hash is primary for efficient lookups I would not want to invest in any iteration speedups if there was a chance of lookup and insertion slowdown. If you are iterating through a Hash all the time then you are probably not using the proper data structure. > In the example I was thinking of, I was using a hash to parse lines in a > file > > identifiers = {/abc/ => 'an abc line', /def/ => 'a def line'} > > string.each_line {|l| identifiers.each{|reg, description| if l =~ reg > then; do something; end } > > So...my particular example I'm only using a hash because of the clean > syntactic look :) [not for the functionality at all]. Ah! > I think that for now I'll just write a Hash monkey patcher a la Why do that? Your identifiers is constant anyway - as far as I can see. Why not just do identifiers = {/abc/ => 'an abc line', /def/ => 'a def line'}.to_a Cheers robert -- use.inject do |as, often| as.you_can - without end