python循环一次释放内存_python 内存释放问题,高手请帮帮忙

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

我重复一楼的问题, range(1024*1024)确实占用很大内存,但是del后,内存几乎是马上就释放了, 没有内存持续占用问题。我测试操作系统是mac ox 10.5.6

在实际应用中,range 对大的数是不适合的,应该用xrange。

可以参考:

http://avinashv.net/2008/05/pythons-range-and-xrange/

Original text: ange and xrange are very different in Python; do you use them correctly? I see a lot of code where the author seemingly didn’t know the difference. At first glance, there doesn’t seem to be one at all—in fact, when I started hacking in Python, I used them interchangeably because I couldn’t figure out what the difference was, and in all the code I was writing at the time, swapping one for the other made no conceivable difference.

It’s a subtle difference. range returns exactly what you think: a list of consecutive integers, of a defined length beginning with 0. xrange, however, returns an “xrange object”, which acts a great deal like an iterator. If you’ve spent anytime with iterators, this difference should make sense. Here’s an example:

range(1000000)

xrange(1000000)

range(1000000) will return a list of one million integers, whereas xrange(1000000) will return (what is essentially) an iterator sequence. Indeed, xrange supports iteration, whereas range does not. The overall benefit is minimal, because xrange (in the words of the Python manual) “still has to create the values when asked for them,” but at each call, it consumes the same amount of memory regardless of the size of the requested list. At extremely large values, this is a major benefit over range. Another benefit is also apparent: if your code is going to break out while traversing over a generated list, then xrange is the better choice as you are going to consume less memory overall if you break.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值