How to improve enumerable find in ruby? -
i making request webservice api , have several ids pointing location. in order re assign results api contains id (sid). have following code:
location.all.each |city| accommodations = accommodation.within_distance(city.lonlat, [1, 2]) lookups << lookup.new(city.id, accommodations.select(:supplier,:sid).to_a.map(&:serializable_hash)) end
after webservice call try re assigning results ids (sid's) cities:
results = call_to_api lookups.each | lup| res << {:city=> lup.city, :accommodations => lup.accommodations.map{ |j| results.find { |i| i.sid == j['sid'] } } } end
the lookups iteration in incredibly slow , takes 50s 4000 entries.
so how can improve performance point of view?
imagine have 3 lookups have accomodations a
, b
, , c
.
the way done now, first lookup perform map , search a
, b
, , c
.
second lookup perform map , search a
, b
, , c
.
and on. given basic nature of search criteria, doesn't results accomodation a
going change between different lookups in same collection.
in case consider caching results of each sid
search , if ever have accomodation same sid
, pull cache.
for example, like
cache = {} if cache.include?(yoursid) // use cache[yoursid] else mappings = //doyourmappinghere // cache future use. might need dup cache[yoursid] = mappings end
of course under assumption same accomodation appears several times.
Comments
Post a Comment