MySQLdb - 游标 - 内存泄漏? [英] MySQLdb - cursor - memory leak?

查看:33
本文介绍了MySQLdb - 游标 - 内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 7 上的 Python32 下使用 MySQLdb:

I'm using MySQLdb under Python32 on Windows 7:

Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)] on win32
>>> import MySQLdb as My
>>> My.version_info
(1, 2, 3, 'final', 0)

我正在运行一次又一次地多次调用此服务的服务:

I'm running service which calls this many times over and over and over again:

cursor = self._connection._conn.cursor()
cursor.execute(sql)
for i in cursor.fetchall(): pass # Operation that is not important
cursor.close()
gc.collect()
return set() # Will be filled with DB data

内存使用量越来越大,我已经尝试过诊断它并以这个结束:

And memory usage just goes up and up and up, I've already tried diagnosing it and end up with this:

83    23.129 MB     0.000 MB           cursor = self._connection._conn.cursor()
84    23.129 MB     0.000 MB           cursor.execute(sql)
85    23.137 MB     0.008 MB           for i in cursor.fetchall(): pass
86    23.137 MB     0.000 MB           cursor.close()
87
88    23.137 MB     0.000 MB           gc.collect()
89
90    23.137 MB     0.000 MB           return set()

__iter__ API 似乎都不是更好:

Neither __iter__ API seems to be better:

84    23.145 MB     0.000 MB           cursor.execute(sql)
85    23.145 MB     0.000 MB           for i in cursor: pass
86    23.152 MB     0.008 MB           cursor.close()
87
88    23.152 MB     0.000 MB           gc.collect()
89
90    23.152 MB     0.000 MB           return set()

并且既不使用 fetchone() 手动循环:

And neither looping manually with fetchone():

84    23.141 MB     0.000 MB           cursor.execute(sql)
85    23.141 MB     0.000 MB           while True:
86    23.141 MB     0.000 MB               row = cursor.fetchone()
87    23.141 MB     0.000 MB               if not row:
88    23.141 MB     0.000 MB                   break
89    23.148 MB     0.008 MB           cursor.close()
90
91    23.148 MB     0.000 MB           gc.collect()
92
93    23.148 MB     0.000 MB           return set()

那么为什么内存清理不回到 23.129MB(为什么它总是使用新的 8KB)?光标有问题吗?我做错了什么吗?

So why is not memory cleaning back to 23.129MB (why it always uses new 8KB)? Is the cursor buggy? Am I doing something wrong?

推荐答案

IIRC cursor.fetchall() 构建内存中的行列表,由于内存分配成本高,Python 倾向于保留内存已经分配.尝试迭代光标,即 for row in cursor: do_something_with(row).

IIRC cursor.fetchall() builds an in-memory list of rows, and since memory allocation is costly Python tends to retains memory already allocated. Try iterating over your cursor instead, ie for row in cursor: do_something_with(row).

这篇关于MySQLdb - 游标 - 内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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