I have one class named Sample which used in my code.
class Sample{
.
.
Object someMethod(){
return someObject;
}
.
.
}
I call like :
Object ob = new Sample().someMethod();
I want to know is there any advantage if I create anonymous Object of any class( new Sample()) and call any require method if I don't have any further use of this Object. I will get any benefits?
I assume that you are asking about the code you posted as contrasted with the following:
(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.