Friday 15 January 2010

java - Memory management : how to reset a list correctly -


In terms of the effect and effect on the garbage collector, I would like to know what is the difference between those two implementations: Protected List & lt; T & gt; _data = new arreelist & lt; T & gt; (); // I want to reset this list using another. Try first: Public Zero Set (list & lt; T & gt; newData) {_data = newData; } / / I want to reset this list using someone else Second attempt: Public Zero Set (List & lt; T & gt; New Data) {_data.clear (); _data.addAll (newData); }

In addition, if there is a functional difference, please tell me!

Replaces the context of a list with the one provided by the previous caller. If the old list has not been reached from anywhere else, then it is eligible for GC.

Uses the current list of second item, and it copies all the items in the list of the caller's references, if it increases the size of the archive, then assigns a large array internally to it. (Small arrays are collected).

The access to the item itself is not to be changed; In both versions the list has been given the reason for referencing the same item.

The first is slightly faster than usual, because you are changing the single reference, it is less work than copying a bunch of references from one list to another.

The second, however, is generally better than a sign point of view. Imagine ...

  yourThingie.set (myItems); MyItems.add (objectYouNeverWouldHaveAllowed);   

With the first version, _data now youNeverWouldHaveAllowed is in. You can no longer apply the barriers of your class to _data ; Since you have dodged the caller in your own list, you now have control over the internal state of your object. They can also break your object from a distance, by mistake.

There is no such problem in the other. You can control the _data , the subsequent changes in the caller's list do not affect you, and if you are not doing something broken (like getting an object that is naked Receives the object), then you secure it

No comments:

Post a Comment