ruby是灵活的,同样的效果花的代价却是不同的请看下面的例子:
require 'benchmark'
Benchmark.bm do|b|
b.report("without .nil?") do
cat = nil
bat = 'vampire'
2_000_000.times do
unless bat
true if cat
end
end
end
b.report("with nil? ") do
cat = nil
bat = 'vampire'
2_000_000.times do
unless bat.nil?
true unless cat.nil?
end
end
end
end
在我的电脑上测试结果如下:
user system total real
without .nil? 0.390000 0.000000 0.390000 ( 0.392000)
with nil? 1.014000 0.000000 1.014000 ( 1.024000)
所以说我们在一些情况下用unless来代替nil?
do_something unless user
或者
unless user
do_something
end
本文通过一个具体的性能测试案例对比了在Ruby中使用nil?和unless的不同性能表现,建议在某些情况下使用unless来替代nil?以提高代码执行效率。
1485

被折叠的 条评论
为什么被折叠?



