如果条件vs &&,是否有任何性能提升

Ros*_*oss 5 ruby ruby-on-rails ruby-on-rails-3

如果用户是所有者,我有条件检查说删除和文章.

delete_article if user.owner?
Run Code Online (Sandbox Code Playgroud)

另一种方式是

user.owner? && delete_article
Run Code Online (Sandbox Code Playgroud)

选择其中任何一个或者只是一种写作风格有什么好处

mar*_*the 6

性能不太可能成为该声明的问题.

第一个更好 - 它更容易阅读.你未来的自我和其他将会参与代码的人会感谢你.


the*_*Man 2

if这里有一些代码来测试VS的速度&&

require 'benchmark'

n = 10_000_000

puts RUBY_VERSION, n
puts

Benchmark.bm(2) do |b|
  10.times do
    b.report('if') { n.times { true if true } }
    b.report('&&') { n.times { true && true } }
  end
end
Run Code Online (Sandbox Code Playgroud)

和输出:

1.9.3
10000000

        user     system      total        real
if   0.970000   0.000000   0.970000 (  0.975714)
&&   1.130000   0.000000   1.130000 (  1.127514)
if   0.950000   0.000000   0.950000 (  0.956892)
&&   1.120000   0.000000   1.120000 (  1.124547)
if   0.970000   0.000000   0.970000 (  0.962618)
&&   1.120000   0.000000   1.120000 (  1.129094)
if   0.960000   0.000000   0.960000 (  0.954498)
&&   1.120000   0.000000   1.120000 (  1.125080)
if   0.960000   0.000000   0.960000 (  0.954001)
&&   1.120000   0.000000   1.120000 (  1.126329)
if   0.950000   0.000000   0.950000 (  0.953360)
&&   1.130000   0.000000   1.130000 (  1.122664)
if   0.950000   0.000000   0.950000 (  0.951391)
&&   1.120000   0.010000   1.130000 (  1.123455)
if   0.980000   0.000000   0.980000 (  0.977263)
&&   1.120000   0.000000   1.120000 (  1.126989)
if   0.970000   0.000000   0.970000 (  0.966264)
&&   1.120000   0.000000   1.120000 (  1.123184)
if   0.960000   0.000000   0.960000 (  0.956702)
&&   1.120000   0.000000   1.120000 (  1.124589)
Run Code Online (Sandbox Code Playgroud)