java : Advantages of anonymous object

2019-02-19 08:02发布

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?

1条回答
老娘就宠你
2楼-- · 2019-02-19 08:09

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.

查看更多
登录 后发表回答