mardi 4 juin 2019

What's best: If statement VS Calculations and operators

In my little coding experience, I have always wondered what was best practice: using if statements and loops, which I find is a lot easier for me to write/read; or achieving the same result using a single (or a few) calculation with some logical operators, which for me takes a lot more thinking and time before coming up with the correct calculation.

Here's an example... Say you want to convert the year (ex. 2019) in days since 01/01/0001, which would be 737059 days according to this matlab code:

>> datenum(datetime(2019,1,1)-datetime(1,1,1))
     737059

You of course have to take into account leap years. The first way to do this would be with a loop and if statements, so something like (in pseudocode):

days = 0
for y = 1 to 2018
  if (y not divisible by 4)
    days = days + 365
  elseif (y not divisible by 100)
    days = days + 366
  elseif (y not divisible by 400)
    days = days + 365
  else
    days = days + 366
  end
end

The other way to do it is with some math and some operators (in MATLAB):

days = (2019-1)*365 + floor((2019-1)/4) - floor((2019-1)/100) + floor((2019-1)/400)

Both alternatives give the same result, but which way do you think would be the "best" way to write code? In which circumstance would one be better than the other?

Aucun commentaire:

Enregistrer un commentaire