开发者

Garbage Collection on objects not assigned to a variable

开发者 https://www.devze.com 2023-02-04 10:58 出处:网络
I am working onproject that uses this pattern var businessEntity = new DAL().GetObject(id); // do something with the business entity.

I am working on project that uses this pattern

var businessEntity = new DAL().GetObject(id);
// do something with the business entity.

Has开发者_如何学编程 anyone followed this pattern?

Does this cause any memory management issues? Any complications with the garbage collector?

Thanks


It works just fine. It will be garbaged collected just fine. Depending on the implementation and the object, either at the end of the line it will be marked for collection, or once businessEntity goes out of scope.


It is very typical code and no, it doesn't cause any problems with the garbage collector.

A reference to the unnamed object is in the VM stack (otherwise the method could not be called), which is in the root set of the GC.


No, the GC eventually will clear the DAL object if nothing else needs to be done with it or nothing else is pointing to it. You have a reference to the businessEntity object, so the GC won't touch it until the reference is invalidated.


This object will be live while its referenced by businessEntry and will be collected sometime after the variable goes out of scope

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号