【发布时间】:2011-07-19 12:14:28
【问题描述】:
我正在编写一个脚本,将数据库信息存储在哈希中,以便以后可以轻松访问。我的代码如下所示:
my_hash = {}
connection.query("select * from ...").each_hash do |row|
date = row['date']
ip = row['ip']
port = row['port']
resp = row['avg_resp_time'].to_i
unless my_hash.key?(ip)
my_hash[ip] = { date => { port => resp } }
else
unless my_hash[ip].key?(date)
my_hash[ip][date] = { port => resp }
else
unless my_hash[ip][date].key?(port)
my_hash[ip][date][port] = resp
end
end
end
end
这只是一个示例,但实际的哈希有时嵌套了 5-6 层,并且需要很长时间才能构建大型结果集。我意识到在构建地图的时间/访问数据的时间之间存在权衡,但我想知道是否有更有效的方法来存储数据,以便在代码中轻松访问,或者让我当前的脚本效率更高一些——这个哈希构建循环是我目前的瓶颈。谢谢。
【问题讨论】:
标签: ruby data-structures performance hashmap