java:匿名对象的优点 [英] java : Advantages of anonymous object

查看:134
本文介绍了java:匿名对象的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Sample 的类,在我的代码中使用。

I have one class named Sample which used in my code.

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


 }
 .
 .
}

我打电话给:

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

我想知道如果我创建匿名对象有任何好处任何类( new Sample())并且如果我没有进一步使用此Object,则调用任何require方法。
我会得到任何好处吗?

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:

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

(您明确指定 new Sample()到局部变量。)

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

这种或那种方式没有显着的性能或内存优势。如果将引用存储在局部变量中然后调用该方法,我认为存储引用可能存在(非常)小的性能损失。但是,我怀疑许多编译器会在调用方法时注意到该变量已经死亡,并且会优化掉分配。 JIT编译器可能会完成这项工作。但我们最多只讨论几个cpu周期。

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.

这篇关于java:匿名对象的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆