Using an inline object method call against declaring a new variable

I have been working with Java and C # for some time now, and I have asked myself this many times, but have not found the answer I was looking for.

When I need to call an object method (this means that it is not static), I have to use the call through an instance of the class, for example:

MyClass myInstance = new MyClass();
myInstance.nonStaticMethod();

I see this code everywhere, so I thought that if a single-line call (example below) behaves differently in terms of performance or just for the sake of standards?

This is what I had in mind in a single line call:

new MyClass().nonStaticMethod();
+4
source share
4 answers

Performance is likely to be the same.

, , new MyClass().nonStaticMethod();, - , ? (.. ?)

: , - (, -), , , - .

+7

-, , - . , , .

, , , , , , Java.

, , , , , , , .

+2

i.e.

MyClass myInstance = new MyClass();
myInstance.nonStaticMethod();

, .. new MyClass().nonStaticMethod(); , . , , new MyClass().nonStaticMethod1();, new object . . , , . , , .

+1
source

Assuming you never need to access the object instance again, there is no difference. Depending on what you prefer.

Of course, if you want to do something else with this object later, you will need it in a variable.

+1
source

All Articles