我正在向webservice API发出请求,我有几个指向某个位置的ID。 为了重新分配来自仅包含id(sid)的API的结果。 我有以下代码:
Location.all.each do |city|
accommodations = Accommodation.within_distance(city.lonlat, [1, 2])
lookups << LookUp.new(city.id, accommodations.select(:supplier,:sid).to_a.map(&:serializable_hash))
end
在网络服务电话之后,我尝试将结果ID(sid&#39; s)分配给城市:
results = call_to_api
lookups.each do | lup|
res << {:city=> lup.city, :accommodations => lup.accommodations.map{ |j|
results.find { |i|
i.sid == j['sid']
}
}
}
end
查找迭代速度非常慢,仅需4000个条目即可达到50秒。
那么如何从绩效的角度改进呢?
答案 0 :(得分:1)
想象一下,您有三个查找都包含A
,B
和C
。
现在,第一次查找将执行地图并搜索A
,B
和C
。
第二次查找将执行地图并搜索A
,B
和C
。
等等。鉴于搜索条件的基本性质,看起来住宿A
的结果实际上会在同一集合中的不同查找之间发生变化。
在这种情况下,我会考虑缓存每个sid
搜索的结果,如果你有相同sid
的住宿,只需将其从缓存中拉出来。
例如,像
cache = {}
if cache.include?(yourSID)
// use cache[yourSID]
else
mappings = //doYourMappingHere
// cache it for future use. Might need to dup
cache[yourSID] = mappings
end
当然,这是假设相同的住宿出现好几次。
答案 1 :(得分:0)
所以这里有提升
ids = Rails.cache.fetch(:ids) {
ids = {}
Location.all.each do |city|
Accommodation.within_distance(city.lonlat, [1, 2]).each do |acc|
if acc.supplier == 2
if ids.include? acc.id
ids[acc.sid] << city.attributes
else
ids[acc.sid] = [city.attributes]
end
end
end
end
ids
}
results = Rails.cache.fetch(:results) {
results = api.rates_by_ids(ids.keys)
}
p results.size
accommodations_in_cities={}
results.each do |res|
ids[res.sid].each do |city|
if accommodations_in_cities.include? city['id']
accommodations_in_cities[city['id']] << res
else
accommodations_in_cities[city['id']] = [res]
end
end
end
accommodations_in_cities
end