0

because i'm a statistician, when i write some code I'm quite concerned about it's efficiency, and now I can't get if there is one of the two following coding styles that's more efficient of the other (I'll show them in python):

def fun(args):
    out= False
    if control(args):
        out= True
    if second_control(args):
        out= True
    return out

or maybe:

def fun(args):
    if control(args):
        return True
    if second_control(args):
        return True
    return False

of course I know I can do both controls whit a 'and' operator, but let's stick on the code above: I always thought that return points break the function and save time, but I tried the code you can see and I found that over 10000 iteration the first one is generally faster, over 1000000 iterations the second one is faster instead.

could someone explain me why does this happen? in fact I'm not even sure my tests are trustworthy.

carlo
  • 247
  • 1
  • 16
  • Possible duplicate of [Should a function have only one return statement?](http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement) – deceze Oct 28 '16 at 09:59
  • Why one or the other may speed up over time can have complex reasons with branch prediction and warming up JIT optimisers, depending on how exactly the code is run. The only real way to figure out which is better ***for your use case*** is by benchmarking it and seeing which one is faster. – deceze Oct 28 '16 at 10:01
  • 3
    The two functions have different behaviour. The first *always* calls `second_control(args)`. It's not just branching optimisation. – khelwood Oct 28 '16 at 10:02
  • thank you for your comments, I didn't find any answer to my question in the previous one you linked, in fact I alredy had found it. – carlo Oct 28 '16 at 10:17
  • 1
    What khelwood said. To get accurate timings you should use the `timeit` module. To get a lower-level view of functions, you can use the `dis` disassembler module. – PM 2Ring Oct 28 '16 at 10:44
  • 1
    Not much to add to previous comments, except that (assuming that the second `if` in your first version should really be a `elif` to make both function equivalent) the second version is the favored Python idiom. wrt/ performances (still assuming etc...) it really shouldn't make that much a difference so I wouldn't worry about it, really. – bruno desthuilliers Oct 28 '16 at 10:54

0 Answers0