python - It is more efficient to use if-return-return or if-else-return?

ID : 20007

viewed : 46

Tags : pythoncperformancecompiler-constructionpython

Top 5 Answer for python - It is more efficient to use if-return-return or if-else-return?

vote vote

93

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1 
vote vote

90

From Chromium's style guide:

Don't use else after return:

# Bad if (foo)   return 1 else   return 2  # Good if (foo)   return 1 return 2  return 1 if foo else 2 
vote vote

76

I personally avoid else blocks when possible. See the Anti-if Campaign

Also, they don't charge 'extra' for the line, you know :p

"Simple is better than complex" & "Readability is king"

delta = 1 if (A > B) else -1 return A + delta 
vote vote

62

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

vote vote

57

Regarding coding style:

Most coding standards no matter language ban multiple return statements from a single function as bad practice.

(Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)

The consensus from all those industry coding standards is that the expression should be written as:

int result;  if(A > B) {   result = A+1; } else {   result = A-1; } return result; 

Regarding efficiency:

The above example and the two examples in the question are all completely equivalent in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.

EDIT :

Sources:

  • MISRA-C:2004 rule 14.7, which in turn cites...:
  • IEC 61508-3. Part 3, table B.9.
  • IEC 61508-7. C.2.9.

Top 3 video Explaining python - It is more efficient to use if-return-return or if-else-return?

Related QUESTION?