ITeye博客

ruby 中尽量少于nil?

fei1985 · 2009-10-31 20:14 · rails · Markdown

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

评论(1)

  1. #1 楼 · lliiqiang · 2014-09-24 13:29

    大家都习惯了一种写法,就成为了社会共同认定规律,而不是个性.

评论功能维护中,当前仅展示历史评论。