为什么这个对象没有被垃圾回收
在下面的代码段中,我想知道为什么在函数调用后没有收集 testvectors
。我看到内存使用量上升到 270Mb,然后永远保持在这个水平。
该函数直接从 Main 调用。
private static void increaseMemoryUsage()
{
List<List<float>> testvectors = new List<List<float>>();
int vectorNum = 250 * 250;
Random rand = new Random();
for (int i = 0; i < vectorNum; i++)
{
List<Single> vec = new List<Single>();
for (int j = 0; j < 1000; j++)
{
vec.Add((Single)rand.NextDouble());
}
testvectors.Add(vec);
}
}
In the following code segment, I am wondering why testvectors
is not collected after the function call. I see memory usage go up to 270Mb and then stay there forever.
This function is directly called from Main.
private static void increaseMemoryUsage()
{
List<List<float>> testvectors = new List<List<float>>();
int vectorNum = 250 * 250;
Random rand = new Random();
for (int i = 0; i < vectorNum; i++)
{
List<Single> vec = new List<Single>();
for (int j = 0; j < 1000; j++)
{
vec.Add((Single)rand.NextDouble());
}
testvectors.Add(vec);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不要将垃圾收集与引用计数混淆。当运行时决定时,内存会被释放,而不总是在不再被引用时释放。引用:
如果您有兴趣,请阅读此内容:
http://msdn.microsoft.com/en-us/library/ 0xy59wtx.aspx
Don't confuse garbage collection with reference counting. The memory is freed when the runtime decides, not always when it's no longer referenced. To quote:
Read this if you're interested:
http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx
GC 可以在需要时运行。那可能要晚得多了。在最后一个引用消失后,没有义务立即释放一些内存。您的阵列将在下一个 Gen2 收集中收集。
除非您继续分配内存,否则函数返回后它可能永远不会运行。
您可以使用 GC.Collect() 手动触发 GC,但通常不鼓励这样做。
The GC can run when it wants. And that can be much later. There is no obligation to free some memory directly after the last reference goes away. Your array will get collected on the next Gen2 collection.
Unless you keep allocating memory, it will likely never run after the function returns.
You can manually trigger a GC with
GC.Collect()
, but that's generally discouraged.当我运行这个时,我观察到相反的情况:
I observe the opposite when I run this:
最有可能的是,您的测试向量被提升到大型对象堆 (LOH),然后在 Gen0 收集期间不会被收集。
很好的链接此处。
Most likely, your testvectors is getting promoted to the Large Object Heap (LOH) and then it is not collected during the Gen0 collection.
Good link here.
垃圾收集是不确定的。由 GC 决定何时是执行此操作的最佳时机。
Garbage collection is non-deterministic. It's up to GC to decide when is a good moment to do it.
尝试添加 GC。 GetTotalMemory(true) 之前和之后的increaseMemoryUsage() 方法使用情况并比较数字。
Try to add GC.GetTotalMemory(true) before and after increaseMemoryUsage() method usage and compare numbers.