for循环内的引用类型变量声明 [英] Reference Type Variable Declaration Inside a for Loop

查看:236
本文介绍了for循环内的引用类型变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们开设一个学生班.形成我们知道的以下代码片段(Java)-

Let we have a Student class. Form the following code snippet (Java) we know -

Student aStudent = new Student();

  1. 已创建学生"类型参考变量
  2. 使用新Student()"创建学生"对象
  3. 该对象分配有参考变量'aStudent'

到目前为止,我知道,每次我们写"new Student()"时,都会创建一个新对象,并为该新创建的对象分配一个内存空间.但是有时候我们会在for循环中写这样的东西-

So far I know, each time we write 'new Student()' a new object is created and the newly created object is allocated a memory space. But sometimes we write something like this in a for loop -

for ( int i=0; i<10000; i++) {
 Student student  = new Student();
 ...
 ...
 ...
}

在这种情况下-

  1. JVM是否会创建Student的新对象10000次?或者在后台进行任何优化以节省内存.
  2. 如果发生任何优化,那么如何完成?以及如何知道for循环中实际创建的对象的数量.

谢谢.

推荐答案

1.JVM是否创建了Student学生的新对象10000次?或者在后台进行任何优化以节省内存.

1.does JVM create new object of Student 10000 times? Or any optimization is occurred behind the scene to save memory.

是的.将创建10,000个Student对象.最后,由于所有对象和引用都将超出范围,因此无法访问它们中的所有10000个(是的,将创建10000个引用.每个对象1个).所有对象和引用(命名为学生)将超出范围,并已准备好用于GC.

Yes. 10,000 Student objects will be created. And at the end all 10000 of them CANNOT be accessed because all the objects and references will go out of scope (yes 10000 references will be created. 1 for each object). All the objects and references (named student) will go out of scope and will be ready for GC.

2.如果发生任何优化,那么该如何完成?以及如何知道for循环中实际创建的对象的数量

2.If any optimization occurred then how it is done? And how can I know the number of actually created object in the for loop

在这种情况下,我不知道编译器会进行任何优化.但是我知道的是,如果您使用诸如codePro之类的静态代码分析工具,它将将此代码标记为警告.也就是说,您不应该在循环中创建对象.

I am not aware of any optimizations being done by the compiler in this scenario. But what I know is if you use a static code analysis tool like codePro, it will mark this code as a warning. i.e, you should not create objects in a loop.

这篇关于for循环内的引用类型变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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