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

查看:52
本文介绍了如何在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 case 会提高性能,因为字节码不会将执行传递到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天全站免登陆