This site requires JavaScript, please enable it in your browser!
Greenfoot back
SPower
SPower wrote ...

2012/5/16

Making yourself null

SPower SPower

2012/5/16

#
Hi all, Is it possible to make yourself null? I tried this:
this = null;
But it doesn't work. Thank you!
nccb nccb

2012/5/16

#
No -- "this" is read-only. What are you trying to accomplish?
SPower SPower

2012/5/16

#
I'm trying to give the garbage collection less to do: if you're null, the garbage collector has less to do.
sp33dy sp33dy

2012/5/16

#
You can put 'null' into an object and once scope of that object is lost, GC will delete it. However, a scenario is required. Also, nulling and object can be the root of memory leaks. I.E. Although people assume GC will clear down all related objects, it doesn't always. Therefore, it's always best to ensure a Class doesn't require delete(), final(), release() or some other method before nulling. However, "I believe" the compiler is clever enough to mark up the points in which the GC will operate to release memory.
SPower SPower

2012/5/16

#
Yeah, buyt an object which is null stands on the heap, will GC delete it or not? It that what you mean with:
sp33dy wrote...
Also, nulling and object can be the root of memory leaks.
sp33dy sp33dy

2012/5/16

#
Here's a great link (look for the response to the post). It's pretty detailed. Great explanation
mjrb4 mjrb4

2012/5/16

#
SPower wrote...
I'm trying to give the garbage collection less to do: if you're null, the garbage collector has less to do.
A few years ago this was an entirely valid thing to do, these days the garbage collector is extremely good at what it does and there's really no need - it counts entirely as premature optimisation (which is a bad thing.) It doesn't really give it "less to do" per se either since it still has to collect unreferenced objects either way; all you're doing is (perhaps) providing the potential for that object to be collected a bit earlier. If you're having issues with garbage collection then chances are you need to do something else to solve it, this isn't the solution! Note though that as already said, "this" is a final keyword - you can't set it to anything else, null included (to allow that would allow all sorts of bizarre behaviour with weird side effects.)
sp33dy sp33dy

2012/5/16

#
>Mjrb4, great response. When optimising my code, I always look to reuse objects were possible, rather than allowing them to be released, garbage collected just because I need to create a new one of the same type, but with different data. Images are a prime example of something worth considering for reuse; where possible.
SPower SPower

2012/5/16

#
Thanks for the explanations!
You need to login to post a reply.