Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

java - Reference Type Variable Declaration Inside a for Loop

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...