Anonymous Variables (?) Benefits?

I was wondering what I thought yesterday.
I apologize in advance for the misleading headline, but I really don't know how to do this. Well, suppose we are two objects ObjA and ObjB , and that, for example, ObjB has a method that takes an ObjA object as an argument.

We can do this (taking java as a language):

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

or

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

Suppose that this is the body of some function, so the objects will be destroyed when leaving the scope. My question is:
do we get a performance advantage by not instantiating special objects and implicitly referring to the second code?
Is it worth the readability?
Or is all this in vain, since implicitly created objects will be stored in memory and in any case die by region?


Note. I don’t know if I say “implicit” or “anonymous” correctly, but I haven’t found much on Google.

+6
source share
3 answers

Absolutely no difference in performance.

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

For ex:

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

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

+6
source

In this case, readability is the only advantage anyway.

There is no significant memory performance or utility. If you store the link in a local variable and then call the method, there may be an extremely limited performance limit for storing the link.

An anonymous object is created and instantly dies. But, still with anonymous objects, work can be retrieved before it dies, like calling a method using an anonymous object:

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

We cannot use twice or more, since an anonymous object dies immediately after completing the assigned task.

+2
source

The first approach, using a named variable, is required if you need to store the object in order to use it several times without creating new objects or keeping the current result of some method that returns the object, if there is a risk (for example, threading) the result will be different the next time. In other cases, it is more convenient to use anonymous objects, since their scope is the same, and there is no namespace with unnecessary identifiers.

+1
source

Source: https://habr.com/ru/post/1014868/


All Articles