如何在python中创建``空if语句'' [英] How to create an 'empty if statement' in python

查看:140
本文介绍了如何在python中创建``空if语句''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中非常常见:像这样黑客空if语句":

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"中没有else情况,则会提高性能,因为字节码不会将执行传递给"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)

以下示例应用程序:

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中创建``空if语句''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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