On Sun, 26 May 2013 16:22:26 -0400, Roy Smith wrote:

> In article <mailman.2196.1369599562.3114.python-l...@python.org>,
>  Terry Jan Reedy <tjre...@udel.edu> wrote:
> 
>> On 5/26/2013 7:11 AM, Ahmed Abdulshafy wrote:
>> 
>> >       if not allow_zero and abs(x) < sys.float_info.epsilon:
>> >                  print("zero is not allowed")
>> 
>> The reason for the order is to do the easy calculation first and the
>> harder one only if the first passes.
> 
> This is a particularly egregious case of premature optimization.  You're
> worried about how long it takes to execute abs(x)?  That's silly.

I don't think it's a matter of premature optimization so much as the 
general principle "run code only if it needs to run". Hence, first you 
check the flag to decide whether or not you care whether x is near zero, 
and *only if you care* do you then check whether x is near zero.

# This is silly:
if x is near zero:
    if we care:
        handle near zero condition()

# This is better:
if we care:
    if x is near zero
        handle near zero condition()


Not only is this easier to understand because it matches how we do things 
in the real life, but it has the benefit that if the "near zero" 
condition ever changes to become much more expensive, you don't have to 
worry about reordering the tests because they're already in the right 
order.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to