【发布时间】:2011-05-09 20:37:12
【问题描述】:
我们在时间紧迫的脚本中有几个地方可以将旧 ID 转换为字符串。目前,我们在函数中使用 case 语句,如下所示:
def get_name id
case id
when 1
"one thing"
when 3
"other thing"
else
"default thing"
end
end
我正在考虑用哈希查找替换它,如下所示:
NAMES = {
1 => "one thing",
3 => "other thing",
}
NAMES.default = "default thing"
感觉使用NAMES[id] 应该比使用get_name(id) 更快——但是是吗?
【问题讨论】:
-
Simon,这是过早的优化。除非您有成千上万的案例,否则我不会费心找出哪一个的性能更高。只关注您的代码。
-
我们只有几个案例,但我们有大约 7,000,000 次查找。
标签: ruby performance