Python:函数中的额外赋值
考虑到以下是 Python 中一个非常简单的函数的两个版本,问题是哪个版本优于另一个版本,为什么?
与需要额外分配的case 2
相比,case 1
是否存在额外的内存使用和/或CPU使用被使用过?
情况1:
def f(x): y = x*x return y
情况2:
def f(x): return x*x
从我的角度来看,情况1
比其他情况更清晰,特别是在复杂计算和提供的情况下许多返回的对象。另一方面,case 2
看起来非常紧凑,并且会被认为是一个非常有吸引力的so。因为简单就是高效。你怎么认为?
更新:
我不知道Python中有反汇编器!当我得知我的问题的答案以及检查类似想法的方法时,真是太神奇了。特别感谢。from dis import dis as dasm
dasm(f)
Considering the following as two versions of a very simple function in Python, the question is which one is preferred over another and why?
Is there any extra memory usage and or CPU usage for case 1
compared to case 2
in which additional assignment has been used?
case 1:
def f(x): y = x*x return y
case 2:
def f(x): return x*x
From my point of view, the case 1
is clearer than the other one especially in case of complex computations and providing many returning objects. On the other hand, the case 2
looks very compact and would be considered as a very attractive so. Since the simple is simply efficient. What do you think?
update:
I didn't know there is disassembler in Python! It was so amazing when I learned the answer of my question and the way to check similar ideas. Special appreciation.from dis import dis as dasm
dasm(f)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想知道首选哪种 Python 风格,请查看标准库中的代码:
您会发现
case 2
风格是最常见的。我个人仅在需要变量名称以增加代码清晰度时才使用赋值形式:
此代码为赋值引入了非常小的一点开销:
If you want to know what Python style is preferred, look at the code in the standard library:
You will see that the
case 2
style is the most common.I personally use the assignment form only when the variable name is needed to add clarity to the code:
This code introduces a very small bit of overhead for the assignment:
对于第一个:
对于第二个:
如您所见,分配某些内容会产生(轻微的)成本,即使您除了在返回之前保留该值之外根本不使用它。
For the first one:
For the second one:
As you can see, there's a (slight) cost in assigning something, even if you're not using it at all except for holding the value before returning.
首选样式是对于该特定功能来说最易读的样式。一旦你有了可读的、正确的代码——你可能就完成了。 如果此时性能是一个问题,请进行分析以查看瓶颈所在,并针对这些点进行处理。
The preferred style is the one which is most readable for that particular function. Once you have readable, correct code -- you are probably done. If performance is an issue at that point, profile to see where the bottlenecks are, and work on those spots.