What are the advantages of an anonymous object?

2.2k Views Asked by At

I have one class named Sample which is used in my code like below:

class Sample{
 .
 .
 Object someMethod(){
  return someObject;


 }
 .
 .
}

I call itlike:

Object ob = new Sample().someMethod();

I want to know if there is any advantage if I create anonymous ``Objectof any class (new Sample()) and call anyrequiremethod if I don't have any further use of thisObject`.

1

There are 1 best solutions below

0
On BEST ANSWER

I assume that you are asking about the code you posted as contrasted with the following:

Sample s = new Sample();
s.someMethod();

(where you explicitly assign new Sample() to a local variable).

There's no significant performance or memory benefit one way or another. If you store a reference in a local variable and then invoke the method, I suppose that there may be an (extremely) small performance penalty for storing the reference. However, I suspect that many compilers would notice that the variable is dead once the method is called and would optimize away the assignment. A JIT compiler might finish the job. But we're talking a few cpu cycles at the most.