Kactung
Kactung

Reputation: 730

Instantiate a class or not?

I'm looking at some lwjgl's tutorials and occurred to me instead of keeping the class instantiated in a variable, instantiate it and call the method directly without saving the object.

I was wondering if it's good to do this when you don't have to reuse the object later, or whether it is best to always keep the object.

I mean this:

(new Lesson02()).run(fullscreen);

instead it:

Lesson02 l2 = new Lesson02();
l2.run(fullscreen);

Thanks.

Upvotes: 2

Views: 141

Answers (7)

Bing_Man
Bing_Man

Reputation: 69

The first way is best accepted because Java can allocate memory for you.

Upvotes: 1

dlev
dlev

Reputation: 48596

The former option will create a temporary reference variable anyway; named or unnamed, you have a local variable referencing an object on the heap. If it's never used again, the garbage collector will clean up for you.

The two options differ only in readability and so you can select the one you prefer from that standpoint.

Upvotes: 2

eyesathousand
eyesathousand

Reputation: 587

The two options are practically identical.

If the compiler is bad at optimising then the first one may infinitesimally be faster, because it is more likely to be quickly reclaimed by the GC.

Upvotes: 2

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43548

Since Java is a garbage collected language, the first way is perfectly accepted. I would prefer it for its compactness and clutterlessness over the second one.

Upvotes: 2

CoolBeans
CoolBeans

Reputation: 20800

There is not really any difference if you do not plan to use the object later. So option 1 is fine. If you follow option 2 and end up not using l2 later in the code then it will get garbage collected anyway.

Upvotes: 3

Daniel
Daniel

Reputation: 31579

I usually use the first option unless there is a lot of parameters to the constructor and function, then I prefer to split it for readability. General rule: use whatever is more understandable and readable.

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

As long as you do not have to use the object later then the first option should be fine.

Upvotes: 2

Related Questions