[英]Python Does creating/assigning a value to a variable every loop take more memory/time than creating/assigning a variable outside the loop?
For example:例如:
for i in range(5000):
a = "some words"
# Other things
vs对比
a = "some words"
for i in range(5000):
# Other things
I'd imagine the second would be better, but how much better exactly is it?我想第二个会更好,但它到底好多少? It might be more efficient to have some code outside a loop but it also feels easier to debug & read when the varaibles are assigned immediately before they are used.在循环外放置一些代码可能更有效,但在使用变量之前立即分配变量时,调试和阅读也更容易。
Intuitively, in vanilla cPython in the absence of a just-in-time compiler that might hoist that assignment out of the loop, we would expect option2 to be faster.直观地说,在普通 cPython 中,由于没有可能将赋值提升到循环之外的即时编译器,我们希望 option2 更快。
See here for more information on " compiler hoisting ".有关“编译器提升”的更多信息,请参见此处。
You can try it for yourself.你可以自己试试。
import timeit
foo = '''
for i in range(5_000):
a = "some words"
'''
bar = '''
a = "some words"
for i in range(5_000):
pass
'''
print(timeit.timeit(foo, number=10_000))
print(timeit.timeit(bar, number=10_000))
Gives me:给我:
1.3565055000000001
0.9187005000000001
Note that this difference in speed is likely meaningless though compared to anything else your app is doing and I would recommend you go with whatever you feel is the easiest to understand and maintain.请注意,尽管与您的应用程序正在执行的任何其他操作相比,这种速度差异可能毫无意义,我建议您选择您认为最容易理解和维护的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.