Java 是“缓存”吗?匿名类?
考虑以下代码:
for(int i = 0;i < 200;i++)
{
ArrayList<Integer> currentList = new ArrayList<Integer>() {{
add(i);
}};
// do something with currentList
}
- Java 将如何处理
currentList
类? - 它会将 200 个对象中的每一个对象视为不同的类吗?
- 即使在创建第一个对象之后,性能也会受到影响吗?
- 它是否以某种方式缓存它?
我只是好奇:)
Consider the following code:
for(int i = 0;i < 200;i++)
{
ArrayList<Integer> currentList = new ArrayList<Integer>() {{
add(i);
}};
// do something with currentList
}
- How will Java treat the class of
currentList
? - Will it consider it a different class for each of the 200 objects?
- Will it be a performance hit even after the first object is created?
- Is it caching it somehow?
I'm just curious :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器会将任何匿名类转换为命名内部类。因此,您的代码将被转换为以下内容:
The compiler is going to transform any anonymous class to a named inner class. So your code, will be transformed to something along the lines of:
每次通过循环都会创建匿名类的新实例,而不是每次都重新定义或重新加载该类。该类定义一次(在编译时),并加载一次(在运行时)。
使用匿名类不会对性能造成重大影响。
is creating a new instance of the anonymous class each time through your loop, it's not redefining or reloading the class every time. The class is defined once (at compile time), and loaded once (at runtime).
There is no significant performance hit from using anonymous classes.