What are the advantages of an anonymous object?

孤街醉人 提交于 2019-12-29 08:07:10

问题


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:


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.



来源:https://stackoverflow.com/questions/27812426/what-are-the-advantages-of-an-anonymous-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!