简体   繁体   English

排除 `else` 会影响 Python 3 的性能吗?

[英]Does excluding the `else` affect the performance in Python 3?

I was looking for an existing answer to this question, and while I came across this answer specifically about C#, this is a compiler-level thing, and so I'd expect Python might differ here.我一直在寻找这个问题的现有答案,虽然我遇到了这个专门关于 C# 的答案,但这是一个编译器级别的事情,所以我希望 Python 在这里可能会有所不同。

Look at these two ways of terminating a function.看看这两种终止函数的方式。 First the one with the else :第一个else

if condition:
    return some_val
else:
    return some_other_val

Then the one without it:然后是没有它的那个:

if condition:
    return some_val
return some_other_val

Logically, the two do precisely the same thing, even if condition has side effects.从逻辑上讲,即使condition有副作用,两者也做完全相同的事情。 They test condition , then return a value.他们测试condition ,然后返回一个值。

Is there a chance that Python 3 optimizes one over the other? Python 3 是否有可能优化其中一个?

找出答案的一种简单方法是在循环中多次(例如 1000 万次),对两者进行计时,然后看看有什么区别。

If you just want to know if there's an optimization, you can use something like snakeviz to know for sure.如果你只是想知道是否有优化,你可以使用诸如snakeviz 之类的东西来确定。 It's difficult to give a hard and fast rule for optimization because each code brings with it different executions.很难给出一个严格的优化规则,因为每个代码都会带来不同的执行。 For example, if you are just doing a simple x + y computation, it might give you an infinitesimally small edge not to include it, where a complex method with a variable input could cause the machine to do more work to comprehend what it's supposed to do.例如,如果你只是在做一个简单的 x + y 计算,它可能会给你一个无限小的边缘来不包括它,其中具有可变输入的复杂方法可能会导致机器做更多的工作来理解它应该做什么做。

From my understanding, it's considered a best practice to always include an else statement.根据我的理解,始终包含 else 语句被认为是最佳实践。 " Explicit is better than implicit. " Always using an else statement gives a hard rule to the program of what to do in each case, it's easier to read (as your code gets more complex) and it will also help you avoid mistakes as you're going. 显式优于隐式。 ” 始终使用 else 语句为程序提供了在每种情况下该做什么的硬性规则,它更易于阅读(随着您的代码变得更复杂),它还将帮助您避免错误去。

For an example of better readability:举个可读性更好的例子:

variable_one = "v1"
variable_two = "v2"
if variable_one.isdigit() == False:
    if variable_one == "a":
        print("The variable is a")
    elif variable_one == "d":
        print("The variable is d")
    if variable_two == "v1":
        pass
if variable_two == "v2":
    print("variable 2 is v2")

While still pointlessly stupid, this code improves readability:虽然仍然毫无意义,但这段代码提高了可读性:

variable_one = "v1"
variable_two = "v2"
if variable_one.isdigit() == False:
    if variable_one == "a": print("The variable is a")
    elif variable_one == "d": print("The variable is d")
    else: pass

    if variable_two == "v1": pass
    else: print ("this variable was not passed")
else: pass

if variable_two == "v2": print("variable 2 is v2")
else: pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM