请考虑以下简化模式:
export class ConteudoprodutoPage {
produto: Produto;
constructor(private payPal: PayPal, public navCtrl: NavController, public
navParams: NavParams) {
this.produto = navParams.get("valor");
}
以及它的重构版本:
def nested_ifs():
if some_condition is True:
# possibly do something
if another_condition is True:
if another is True:
return do_this()
# or do something else
return None
从可读性的角度来看,我个人更喜欢def flat_ifs():
if some_condition is not True:
# or do something else
return None
# possibly do something
if another_condition is not True:
return None
if another is not True:
return None
return do_this()
的处理方式,但是性能上有区别吗?
答案 0 :(得分:0)
令人惊讶的是,似乎嵌套循环实际上稍微快一点:
import datetime
def nested_ifs(x):
if True:
if True:
if True:
return 10*x
return None
def flat_ifs(x):
if not True:
return None
if not True:
return None
if not True:
return None
return 10*x
nr = 100000000
begin = datetime.datetime.now()
for i in range(nr):
nested_ifs(i)
print("nested", datetime.datetime.now() - begin)
begin2 = datetime.datetime.now()
for i in range(nr):
flat_ifs(i)
print("flat", datetime.datetime.now() - begin2)
给予我们
nested 0:00:14.960115
flat 0:00:16.157715
即使其中一个条件失败,也是如此。
如果有人能评论为什么嵌套方式要快一点的话,我将不胜感激