我的模型中有一个非常昂贵的方法,可以比较许多项目的数组文本项目。
它运行 真的很慢。如果我使用关系数据库表并仅比较 ID,我的方法会运行得更快吗?
/编辑
我正在尝试对以下内容进行基准测试:
@matches = @location_matches.sort do |l1, l2|
l1.compute_score(current_user) <=> l2.compute_score(current_user)
end
@matches.reverse!
最佳答案
简而言之,我猜数字比较会更快,因为比较字符串是关于一个又一个字符的比较(建议:在 Ruby 中尽可能使用符号,它们的比较要快得多)。
不管怎样,您都会找到 there ,这是您进行基准测试和获得详细结果所需的一切。
代码示例:
require 'benchmark'
n = 50000
Benchmark.bm do |x|
x.report("for:") { for i in 1..n; a = "1"; end }
x.report("times:") { n.times do ; a = "1"; end }
x.report("upto:") { 1.upto(n) do ; a = "1"; end }
end
结果:
user system total real
for: 1.050000 0.000000 1.050000 ( 0.503462)
times: 1.533333 0.016667 1.550000 ( 0.735473)
upto: 1.500000 0.016667 1.516667 ( 0.711239)
关于mysql - rails - 数字比较与文本比较的速度有多快,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6849999/