python中空语句,如何在python中创建``空if语句''

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

if(mostlyhappencondition)

;#empty statement

else{

dosomething;

}

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

解决方案

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.

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

The following sample app:

def foo(x):

if x:

pass

else:

return x+2

Disassembles to:

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

The following

def foo(x):

if not x:

return x+2

Disassembles to:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值