使用if-return-return或if-else-return更有效率? [英] It is more efficient to use if-return-return or if-else-return?

查看:347
本文介绍了使用if-return-return或if-else-return更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 if 语句与 return 。从效率的角度,我应该使用

  if(A> B):
return A + 1
return A-1

  if(A> B):
return A + 1
else:
return A-1

使用编译语言(C)或脚本语言(Python)时,我应该选择其中一种吗?


<因为 return 语句终止当前函数的执行,这两种形式是等价的(虽然第二种形式一个比第一个更可读。)



两个表单的效率是可比的,如果的底层机器代码必须执行跳转,如果条件为false,无论如何。



注意Python支持一个语法,只允许使用一个 code>语句:

 如果A> B else A-1 


Suppose I have an if statement with a return. From the efficiency perspective, should I use

if(A > B):
    return A+1
return A-1

or

if(A > B):
    return A+1
else:
    return A-1

Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?

解决方案

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

这篇关于使用if-return-return或if-else-return更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆