Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if condition vs &&, is there any performance gain

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

delete_article if user.owner?

Another way is

user.owner? && delete_article

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

like image 357
Ross Avatar asked Jan 17 '13 13:01

Ross


3 Answers

Performance is unlikely going to be an issue with that statement.

The first one is much better - it's easier to read. Your future self and others who'll get to work on the code will thank you for it.

like image 124
marcel salathe Avatar answered Oct 17 '22 16:10

marcel salathe


You can use both styles but there are some differences in the logic.

Used in a method call:

def something
  delete_article if user.owner?
end

would return whatever the the method delete_article returns or nil if the user is not the owner.

With:

def something
  user.owner? && delete_article
end

it would return false if the user is not an owner. If the user is an owner it would return whatever the method delete_article returns.

Performance should be about the same.

like image 40
spas Avatar answered Oct 17 '22 16:10

spas


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

And the output:

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)
like image 2
the Tin Man Avatar answered Oct 17 '22 16:10

the Tin Man