IronPython 内存泄漏?

发布于 2024-08-30 07:46:42 字数 860 浏览 2 评论 0原文

运行这个:

for i in range(1000000000):
    a = []

看起来正在创建的列表对象永远不会被标记为垃圾回收。从内存分析器来看,解释器的堆栈帧似乎保存着所有列表对象,因此 GC 永远无法对此执行任何操作。

这是设计使然吗?

编辑:

这是问题的一个更好的例子。使用内存分析器运行下面的代码:

a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]

您将看到在列表推导期间分配的内存永远不会被垃圾收集。这是因为创建的所有对象都由 DLR 中的 InterpreterFrame 对象引用。

现在运行这个:

def get():
    return [b for b in range(1000000)]

a = get()
a = get()
a = get()
a = get()
a = get()
a = get()
a = get()

在分析器下,您可以看到这里的内存确实按照应有的方式进行了垃圾收集。我猜这是可行的,因为函数退出时函数的 InterpreterFrame 被清除。

那么,这是一个错误吗?这似乎在 IronPython 脚本的框架(上下文?)内会导致一些非常严重的内存泄漏。

Run this:

for i in range(1000000000):
    a = []

It looks like the list objects being created never get marked for garbage collection. From a memory profiler, it looks like the interpreter's stack frame is holding onto all the list objects, so GC can never do anything about it.

Is this by design?

EDIT:

Here is a better example of the problem. Run the code below with a memory profiler:

a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]
a = [b for b in range(1000000)]

You will see that the memory allocated during the list comprehensions never gets garbage collected. This is because all the objects created are being referenced by an InterpreterFrame object in the DLR.

Now run this:

def get():
    return [b for b in range(1000000)]

a = get()
a = get()
a = get()
a = get()
a = get()
a = get()
a = get()

Under a profiler, you can see that the memory here does get garbage collected as it should. I am guessing this works because the InterpreterFrame of the function is cleared when the function exits.

So, is this a bug? This seems that it will lead to some pretty bad memory leaks when within frames (contexts?) of an IronPython script.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落日海湾 2024-09-06 07:46:42

在构建 IronPython 引擎时尝试设置“LightweightScopes”。这为我解决了很多垃圾收集问题。

var engineOptions = new Dictionary<string, object> { ["LightweightScopes"] = true };
var scriptEngine = Python.CreateEngine(engineOptions);

Try setting "LightweightScopes" when you are constructing IronPython engine. This solved a lot of garbage collection problems for me.

var engineOptions = new Dictionary<string, object> { ["LightweightScopes"] = true };
var scriptEngine = Python.CreateEngine(engineOptions);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文