Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inline object method call vs. declaring a new variable

Tags:

java

c#

oop

I have been working with Java and C# for a while now and I've been asking myself this many times but haven't ever found the answer I was looking for.

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

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

I see this kind of code everywhere, so I was thinking if one-line call (example below) is behaving differently performance wise or it's just the sake of standards?

This is what I meant with one-line call:

new MyClass().nonStaticMethod();
like image 302
Marko Gresak Avatar asked Nov 01 '13 21:11

Marko Gresak


3 Answers

The performance would probably be the same.

However, having calls such as new MyClass().nonStaticMethod(); usually reeks of a code smell - what state was encapsulated by the object that you only needed to invoke a method on it? (i.e. Why was that not a static method?)

EDIT: I do not intend to say it is always bad - in some cases, such idioms are encouraged (such as in the case of fluent builder objects) - but you will notice that in these cases, the resulting object is still significant in some way.

like image 126
Jean Hominal Avatar answered Oct 14 '22 01:10

Jean Hominal


I would go with the first way i.e.

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

The problem with the second one i.e. new MyClass().nonStaticMethod(); is in case you want to call another method from same object you don't have any choice The only thing you can do is new MyClass().nonStaticMethod1(); which actually creates a new object everytime. IMHO I don't think any one of them would performance better than the other. IN lack of performance gain I would definitely choose the one which is more clear and understandable hence my choice.

like image 23
Prateek Avatar answered Oct 14 '22 00:10

Prateek


If you look at the byte code generated you can prove there is absolutely no different to the performance or anything else. Except you are using a local variable which should be discarded.

Unless you have measured that you have a performance problem, you should assume you don't and guessing where a performance problem might be is just that, no matter how much experience you have performance optimizing Java applications.

When faced with a question like this, you should first consider what is the simplest and clearest, because the optimizer looks for standard patterns and if you write confusing code, you will not only confuse yourself and others but the optimizer as well and it is more likely to be slower as a result.

like image 35
Peter Lawrey Avatar answered Oct 14 '22 02:10

Peter Lawrey