GeeCON Prague 2014*
The moose likes Java in General and the fly likes Difference between arraylist.clear(); arralist=null Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference between arraylist.clear(); arralist=null" Watch "Difference between arraylist.clear(); arralist=null" New topic
Author

Difference between arraylist.clear(); arralist=null

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
hi i am using very big collection of elkements in an arraylist
ArrayList arraylist =new ArrayList(8000);
arraylist.add("1");......
....
...
arraylist.add("8000");

after the utilization of this arraylist i am trying to destroy it means allowing the garbage collector to free the space.

for this i am using arraylist.clear();

but some uses arraylist=null;

which is the better way



thanks in advance


A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

According to my understanding by clearing the arraylist doesn't means that the arraylist is no longer referenced anywhere else. it may be used because it doesn't release the memory reference.

But by doing like.


we mean by above code is that this variable is no longer refereed. That mean is eligible for Grabage Collector.

Please correct me if I am wrong...
vijaya bharath
Ranch Hand

Joined: Jun 10, 2005
Posts: 66
hi,

if u say arraylist = null means u r saying xplicitly to the garbage collector that no more u use this arraylist. but when u say clear(), it means u may add some other values to this arraylist.


Regards,<br />Vijaya Bharath.<br />SCJP1.4 <br />SCWCD5.0
mohit bahl
Ranch Hand

Joined: Mar 22, 2006
Posts: 48
Hi,
arrayList.clear() sets all the objects contained in an arraylist to null. But this does not ensure that all the objects contained in the arraylist will be garbage collected. The objects which have references elsewhere will not be GCed till all references are removed.

And arraylist = null just sets its reference to null and will not be garbage collected till there are references to it and the objects contained in it will also be GCed as explained above.

As you will never know when the GC will be done and hence you cannot force GC by setting your objects to null. The objects will get GCed as and when the objects go out of scope.

i hope this helps
cheers!


to err is human, but the company policy doesn't allow it!
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42031
    
  64
In short: calling clear() helps, unless you're referencing the objects from elsewhere as well. Setting arraylist to null doesn't do much, especially as the list itself doesn't take up much space - its elements do.


Ping & DNS - my free Android networking tools app
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
Also, setting a reference to null inside a method which was passed that list as a parameter will have no effect outside that method unless it's then returned to the calling method as the return value of that method and assigned back to its original.
Calling clear on a list inside a method which was passed that list as a parameter WILL have the effect of emptying the list as it is seen outside that method (as all method calls on the list would).


42
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Originally posted by mohit bahl:
Hi,
arrayList.clear() sets all the objects contained in an arraylist to null. But this does not ensure that all the objects contained in the arraylist will be garbage collected. The objects which have references elsewhere will not be GCed till all references are removed.

And arraylist = null just sets its reference to null and will not be garbage collected till there are references to it and the objects contained in it will also be GCed as explained above.

As you will never know when the GC will be done and hence you cannot force GC by setting your objects to null. The objects will get GCed as and when the objects go out of scope.

i hope this helps
cheers!

ya u r right we cannot force by setting null to araylist but it will get eligbility for garbage collection so it may happend at any time..

so we must first clear the arralist elements after tht we must keep null value tot he arraylist
arraylist.clear();
arraylist=null;



Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by saikrishna cinux:

so we must first clear the arralist elements after tht we must keep null value tot he arraylist


Actually, the best thing to do is nothing. Write short methods, keep the scopes of variables as small as possible, and just let them be collected when they fall out of scope. You're wasting a lot of mental energy worrying about things that (forgive me) you don't understand well enough yet to concern yourself with. Java's garbage collector will take care of things for you, if you just stay out of its way.

Keeping the scopes of variables small, by the way, means using local variables instead of fields whenever possible, and writing many short methods instead of a few long ones.

[ EFH: Corrected "locals" to "fields", as suggested below -- thanks! ]
[ June 06, 2006: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Keeping the scope of variables small and writing many short methods is a recipe for intensive garbage collection. Not saying that makes it bad. But its a consideration.

If you are clearing this array very frequently, then setting the reference to null potentially creates another object to GC every time you do this also means you need to instantiate a new object. If you use clear() you do not create another object that needs to be GCed and you do not need to instantiate another object.

So the question is, how frequently are you doing this? IMHO, clear() is preferred either way.
stephen shields
Greenhorn

Joined: Jun 05, 2006
Posts: 20
if you think about it in c++ terms, which doesnt have garbage collection, lol
then just clear it "arraylist.clear() which should set every element to null
and then arraylist = null; that is if u are worrying about garbage collection
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Ernest Friedman-Hill:


Actually, the best thing to do is nothing. Write short methods, keep the scopes of variables as small as possible, and just let them be collected when they fall out of scope. You're wasting a lot of mental energy worrying about things that (forgive me) you don't understand well enough yet to concern yourself with. Java's garbage collector will take care of things for you, if you just stay out of its way.

Keeping the scopes of variables small, by the way, means using local variables instead of locals whenever possible, and writing many short methods instead of a few long ones.


I believe he meant "local variables instead of fields/instance variables".
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Mr. C Lamont Gilbert:
Keeping the scope of variables small and writing many short methods is a recipe for intensive garbage collection. Not saying that makes it bad. But its a consideration.

If you are clearing this array very frequently, then setting the reference to null potentially creates another object to GC every time you do this also means you need to instantiate a new object. If you use clear() you do not create another object that needs to be GCed and you do not need to instantiate another object.

So the question is, how frequently are you doing this? IMHO, clear() is preferred either way.


Allocation and collection of short lived objects is cheap or even free. The scope of a variable should be no more than is necessary. You're advocating attempting to keep an object without any knowledge about how the object is used or whether or not it should be reused.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Ken Blair:


Allocation and collection of short lived objects is cheap or even free. The scope of a variable should be no more than is necessary. You're advocating attempting to keep an object without any knowledge about how the object is used or whether or not it should be reused.


I made a resonable assumption, albeit it is an assumption. If he has a choice between clear or =null, thats giving me some context. I go with clear. Nothing is free.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Okay, fine but I prefer not to leave 30mb in memory sitting around unused because I have a variable exposed to excessive scope. An array of 8000 references occupies just as much space when the references are null.
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
Originally posted by Mr. C Lamont Gilbert:


I made a resonable assumption, albeit it is an assumption. If he has a choice between clear or =null, thats giving me some context. I go with clear. Nothing is free.


In case you'd not realised it yet, calling clear() will give you only a few bytes difference in the amount of memory released for GC compared with setting the List to null (or better yet, just letting it go out of scope).
Your assumption is wrong.
In fact, you're using a rather expensive operation where doing nothing would have exactly the same effect had you designed your program properly.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Out of curiousity, I attempted to test just how much of a difference there was. For those interested:



The output I got was:

First method took: 29641ms
Second method took: 29453ms

Now does anyone see a problem with my test? Not that I'm overly concerned about the performance to begin with. The OP seems to be asking a rather general question and hasn't actually presented any information on what they're actually doing or where the performance bottleneck lies. I'm just wondering if there's a flaw in the test or if others get the same result because I honestly didn't expect it to be that close.
[ June 07, 2006: Message edited by: Ken Blair ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
The reasons the numbers are so close are because (a) there really is little difference between the two, but also (b) in your test, the number of iterations of the inner loop is so high that the time spend performing add() is dwarfing the time spent performing GC. You can see more pronounced differences by setting the inner loops to 2, 1, or even 0 iterations, and increasing the outer loop size accordingly. Still, it's rare that the difference will matter, I think. By replacing the ArrayList rather than claring it, we may on rare occasions get slower performance - but we also have the advantage of being less likely to be using more memory than needed (since clear() does not trimToSize() the internal array). Note also that most code will do something else with the data along the way, which typically ends up taking more time than the minuscule effects we're trying to measure here.
[ June 07, 2006: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
I actually figured Iterator.toString(int) would consume most of the time. Which is part of the point really, that allocation and collection are so fast in Java, particularly with short-lived objects, that there's a good chance any performance difference between the two will be eclipsed by the code surrounding it. And the inner loop was so large because that's exactly what the OP said s/he was doing. If the time spent doing something with the list was miniscule I'm sure the difference would become noticeable, but that hardly seems representative of a real application.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yup, all true. (I overlooked the Integer.toString() part.) To the extent you were surprised the results were so close, I was addressing why they were so close, and what sort of conditions would differentiate them more. I agree for the vast majority of real applications, this ends up a complete non-issue.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between arraylist.clear(); arralist=null