Reference Type Variable Declaration Inside a for Loop

南楼画角 提交于 2019-12-25 17:01:54

问题


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

Student aStudent = new Student();
  1. A 'Student' type reference variable is created
  2. An object of 'Student' is created with the 'new Student()'
  3. The object is assigned with the reference variable 'aStudent'

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();
 ...
 ...
 ...
}

In this situation -

  1. does JVM create new object of Student 10000 times? Or any optimization is occurred behind the scene to save memory.
  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.

Thanks in advance.


回答1:


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

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.If any optimization occurred then how it is done? And how can I know the number of actually created object in the for loop

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.




回答2:


Sorry if this answer isn't accurate since I'm relatively new to Java.

From my understanding yes 10000 objects will be created but all but 1 of them will be eligible for Garbage collection since there is nothing pointing to the other objects.

The Garbage collector is the only optimization that goes on behind the scenes, however it cannot be called directly but you can suggest for an object to be garbage collected by simply setting it to null ie: student = null;



来源:https://stackoverflow.com/questions/23221447/reference-type-variable-declaration-inside-a-for-loop

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