如果条件 vs &&,是否有任何性能提升 [英] if condition vs &&, is there any performance gain

查看:37
本文介绍了如果条件 vs &&,是否有任何性能提升的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a condition to check say delete and article if user is owner.

delete_article if user.owner?

另一种方式是

user.owner? && delete_article

选择它有什么好处吗,或者只是一种写作风格

is there any benefit in choosing either of it or is it just a writing style

推荐答案

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

Here's some code to test the speed of 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

和输出:

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)

这篇关于如果条件 vs &&,是否有任何性能提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆