[MacRuby-devel] Question on Hash performance
Robert Rice
rice.audio at pobox.com
Thu Jan 13 23:05:51 PST 2011
I suspect that there is considerably more overhead in creating a Hash as compared to an Array and that using an Array is more efficient unless the Array will become large. I am wondering about how large the Array would have to be before it becomes more efficient to use a Hash. Consider the following example:
class Test
def initialize
@array = []
@hash = {}
end
def get_from_hash( key )
@hash[ key ]
end
def set_hash( key, value )
value.nil? ? @hash.delete( key ) : @hash[ key ] = value
end
def get_from_array( key )
pair = @array.assoc( key )
pair ? pair.last : nil
end
def set_array( key, value )
pair = @array.assoc( key )
if pair
value.nil? ? @array.delete( pair ) : pair[1] = value
else
@array << [ key, value ] unless value.nil?
end
end
end
Clearly it requires more code to emulate the hash function with an Array, but would it run faster for a small number of keys?
Bob Rice
More information about the MacRuby-devel
mailing list