python中被覆盖的变量会发生什么? [英] What happens to overwritten variables in python?

查看:72
本文介绍了python中被覆盖的变量会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些 Python 代码来处理大量数据(将近 600 万条!).在代码中,我使用了一个巨大的 for 循环来处理每个集合.在那个循环中,我在每个循环中都使用相同的变量并覆盖它们.当我运行程序时,我注意到我运行它的时间越长,它变得越慢.此外,在进一步的实验中,我发现如果你对 10,000 - 10,100 的值运行它的速度与从 0 到 100 的速度相同.因此我得出结论,因为我没有创建更多的变量而只是处理现有的变量,每次我覆盖一个变量,它必须被python保存在某个地方.

I am writing some python code to process huge amounts of data (almost 6 million pieces!). In the code, I'm using a huge for loop to process each set. In that loop, I'm using the same variables every loop and overwriting them. When I ran the program, I noticed that the longer I ran it, the slower it got. Furthermore, upon further experimenting, I discovered that the speed if you ran it for values 10,000 - 10,100 was the same as from 0 to 100. Thus I concluded that since I was not creating more variables and merely processing existing ones, every time I overwrote a variable, it must be being saved somewhere by python.

所以:我对吗?一定是python将我的覆盖保存在某处吗?还是我错了?有其他事情发生吗?

So: Am I right? must it be python saving my overwritten somewhere? Or am I wrong? Is something else happening?

推荐答案

Python 使用引用计数来跟踪变量.当对一个变量的所有引用都被删除时,该变量将被垃圾收集.然而,垃圾收集是由 python 自己的心血来潮完成的,而不是立即完成.

Python uses reference counting to keep track of variables. When all references to a variable are removed, that variable is garbage collected. However that garbage collection is done by python at it's own whim, not right away.

可能是你的代码比 python 垃圾收集器运行得更快,或者你的代码有问题.由于您没有提供任何代码,因此无法真正知道.

It could be that your code is going faster than python garbage collects, or that you have something wrong with your code. Since you didn't give any of your code there's no real way to know.

这篇关于python中被覆盖的变量会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆