无限循环中创建的对象的垃圾回收 [英] Garbage collection of the object created in infinite loop
本文介绍了无限循环中创建的对象的垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常基本的问题.
I have a very basic question.
我这样写一个循环:
while(true)
{
MyTestClass myObject = new MyTestClass();
}
- 何时在中创建对象循环中,垃圾被收集了吗?
- 也是,每次迭代都是新的内存位置是分配给myObject引用?
- 如果我在每次迭代结束时都写
myObject = null;
,该怎么办?
- When will be the object created in the loop, garbage collected?
- Also, for every iteration, is it that the new memory location is allocated to the myObject reference?
- What if i write
myObject = null;
at the end of every iteration?
推荐答案
- 坦率地说,只要GC有这种感觉,该变量从不读取,因此始终符合条件
-
myObject
是变量-在堆栈上具有固定位置以供参考;但是,每个new MyTestClass()
是一个不同的 object ,它们在可用堆空间中的某个位置创建;每次都不同 - 没有任何区别;严格来说,存在一些复杂性,涉及变量的实际声明点(在IL中)以及
while
的实际实现方式-但这仅在退出循环后才会显示.而且由于您在每次迭代时都会立即分配它,所以这里没有有形差异
- whenever GC feels like it, frankly; the variable is never read, so it is always eligible
myObject
is the variable - that has a fixed position on the stack for the reference; however, eachnew MyTestClass()
is a different object, created somewhere in the available heap space; different each time- no difference whatsoever; strictly speaking there are some complexities involving the actual declaration point of the variable (in IL) and how
while
is actually implemented - but that would only show after exiting the loop. And since on each iteration you immediately allocate it, there is no tangible difference here
这篇关于无限循环中创建的对象的垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文