Anonymous Variables (?) Advantages?

Anonymous Variables (?) Advantages?

I was wondering about one thing that jumped into my mind yesterday.
I apologize in advance for the misleading title, but I really don't know how to entitle this.

Well, suppose we are two objects ObjA and ObjB, and that, for instance, ObjB has a method that takes an ObjA object as argument.

We can do this (taking java as language):

ObjA instanceA = new ObjA();
ObjB instanceB = new ObjB();

instanceB.method(instanceA);

or

new ObjB().method(new ObjA());

Assume this is the body of some function, so the objects will be destroyed when going out of scope.

My question is:
do we get a performance advantage by not instantiating the singular objects and calling the implicitly as for the second code?
Is this readability sacrifice worth something?
Or is it all for nothing since the implicitly created objects will be stored in memory and die by scope anyway?


Note: I don't know if I'm saying right with "implicit" or "anonymous", but I have not found much on Google.

7

3 Answers

Absolutely no difference performance wise.

But in few cases, you will be forced to use first type.

For ex :

ObjA instanceA = new ObjA();
// Do something with instanceA
instanceB.method(instanceA);

If you have nothing to do in middle, I can just use the second way to save a line of code.

0

In this case readability is the only advantage one way or another.

There's no significant performance or memory benefit.If you store a reference in a local variable and then invoke the method,there may be an extremely small performance penalty for storing the reference.

The anonymous object is created and dies instantaneously. But, still with anonymous objects work can be extracted before it dies like calling a method using the anonymous object:

 new ObjB().method(new ObjA());

We can’t use twice or more as the anonymous object dies immediately after doing its assigned task.

The first approach using named variable is required if you need to store the object to use it several times without creating new objects or to store the current result of some method returning an object if there is a risk (e.g. because of multi-threading) the result will be different the very next time. In other cases it's more convenient to use anonymous objects since their scope is the same and there is no namespace cluttering with unneeded identifiers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.