Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Object Reuse - request for opinions

Status
Not open for further replies.

idarke

Programmer
Jul 23, 2001
420
US
I've read here and there that object reuse is a good thing to do - fewer objects, better garbage collection, faster execution, etc. So instead of doing this:

Foo f1 = new Foo();
f1.doSomething();
Foo f2 = new Foo();
f2.doSomething();

I've been doing this:

Foo f1 = new Foo();
f1.doSomething();
f1 = new Foo();
f1.doSomething();

and patting myself on the back for reusing an object. But lately I've been wondering if this is really buying me anything. So I'm asking the question in hopes of learning - is this object reuse? Is it worth doing? And if it isn't, what is?

Thanks in advance...
Idarke "When you have eliminated the impossible, whatever remains, however
improbable, must be the truth." ~ Arthur Conan Doyle
 
In general, yes. Your second implementation could result in the first instance of Foo being released from memory by the garbage collection earlier. The likelihood of that depends almost entirely on the associated code and in many cases may not make any difference. Still it is a good habit to use as it should rarely, if ever, negatively impact performance.

Now is that specifically what someone was referring to using the term “object reuse”? Maybe, or maybe they were referring to the OO design principle of reuse. In that context it means something completely different.

Hope that helps
-pete

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top