简体   繁体   中英

What will be better way to clear Array in concern of Memory

**** EDIT *****

There is a question - here , I have gone through. My Purpose of asking is different (as in that question, asker is asking for solution(s) which he got. and here I'm looking for better way to accomplish the task (I know two solutions and asking better one or even better 3rd option))


I have an array of Obj . I know these two ways which are clearing (or doing similar) an Array.

int length = arrayOfObj.Length

1: arrayOfObj = new Obj[length]

2: Array.Clear(arrayOfObj, 0, length)

they both are apparently doing the same thing. But which one of this is better in terms of Memory. Or I should leave this matter of Internal Garbage collection ?

You don't have to worry about it. As you suggested, garbage collection will take care of it for you. However, if you still have references elsewhere to any of the objects that were in your array, those objects, of course, won't be garbage collected.

I should also mention something about IDisposable as suggested by the comments under your question. The .NET framework's garbage collector will release managed resources when appropriate. The purpose of the IDisposable interface is to guarantee that unmanaged resources get released, such as open files and streams. If the class whose objects are in your array have any such unmanaged resources, the class should implement IDisposable and you should call Dispose on every object before you clear the array.

Normally when dealing with IDisposable , you would utilize the using statement to guarantee that the object was properly disposed when you're done with it. However, since you are dealing with a collection of disposable objects in this case, it's unlikely each object was created inside a using statement (it could be possible in some extravagant scenario). Therefore, you must loop through the elements and call Dispose on each one before you clear the array**. This, again, is only if the objects in your collection have unmanaged resources that need to be dealt with before each object is garbage collected.

** Keep in mind: you'll run into trouble if you have external references to any of those objects and try to use them again afterward since they will have already been disposed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM