在python中'empty if statement'怎么样? [英] How about 'empty if statement' in python

查看:133
本文介绍了在python中'empty if statement'怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中很常见:黑客'如果声明'这样:

It's very common in C: hacking 'empty if statement' like this:

if(mostlyhappencondition)
    ;#empty statement
else{
    dosomething;
}

它在Python中运行?我的意思是,我们可以通过使用它来改善应用程序的性能吗?我也想知道原因。

It's working in Python? I mean, can we improve the app's performance by using that? I'd also like to know why.

推荐答案

如果中没有其他情况,性能会有所提高if,因为字节码不会将执行传递给if情况。

There is a performance improvement if there isn't an else case in the "if", since the bytecodes don't pass execution into the "if" case.

这里有一些函数和输出 dis.dis(foo)

Here's some functions and the output of dis.dis(foo)

以下示例应用程序:

def foo(x):
    if x:
        pass
    else:
        return x+2

反汇编为:

5           0 LOAD_FAST                0 (x)
            3 POP_JUMP_IF_FALSE        9

6           6 JUMP_FORWARD             8 (to 17)

8     >>    9 LOAD_FAST                0 (x)
           12 LOAD_CONST               1 (2)
           15 BINARY_ADD          
           16 RETURN_VALUE        
      >>   17 LOAD_CONST               0 (None)
           20 RETURN_VALUE        

以下

def foo(x):
    if not x:
        return x+2

反汇编为:

11           0 LOAD_FAST                0 (x)
             3 POP_JUMP_IF_TRUE        14

12           6 LOAD_FAST                0 (x)
             9 LOAD_CONST               1 (2)
            12 BINARY_ADD          
            13 RETURN_VALUE        
       >>   14 LOAD_CONST               0 (None)

这篇关于在python中'empty if statement'怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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