Reputation: 295
Sometimes we found a reference type variable declared inside a for loop like this -
for(int i=0; i<1000; i++){
User aUser = new User(id);
//some other code
}
My question are -
1. Is there any decrease in performance for declaring a reference type variable inside a for loop?
2. Does the memory contains 1000 user object at a time?
Thanks in advance.
Upvotes: 2
Views: 154
Reputation:
ThreadLocalHeap avoid acquiring heaplock for object allocation. It does not allocate large objects. It could allocate objects of size 512 bytes beyond that JVM do allocation on java heap which involves Heap lock. If the User object of < 512 bytes then there are less possibilities in performance degradation but anyhow all 1000 objects will present in the java heap.
Upvotes: 2
Reputation: 1132
Is there any decrease in performance for declaring a reference type variable inside a for loop?
Whenever new object allocated JVM acquires heaplock for doing allocation. Yes there might be slight performance degradation because of repeated process of acquiring lock and release.
Does the memory contains 1000 user object at a time?
Yes Java heap will contain 1000 user object. GC will clean these objects if it does not have any strong outgoing/incoming reference to this object.
Upvotes: 1
Reputation: 484
There may be a slight performance hit if you allocate a new reference for each iteration. It would be just as easy to declare User aUser; before entering the loop. However, I doubt the performance loss would be very noticeable, if at all.
The memory used by the variable aUser should be recycled after each iteration. This may not happen instantly (Java doesn't guarantee when garbage collection will happen)
Upvotes: 1
Reputation: 24157
Is there any decrease in performance for declaring a reference type variable inside a for loop?
You will be creating new reference to point to a new object in this case. Even if you move the reference User aUser
out of the loop even then it will lead to creation of 1000 objects but reference variable will not be created again and again. IMO you can move reference variable out but it may not cause big performance change as such. But when to use what depends. IMO if the reference variable is out of the loop it will end up pointing to last created Object in loop but if it is inside then all the references and objects to which they point will be ready for garbage collection.
Does the memory contains 1000 user object at a time?
Yes it may until they are all garbage collected by GC and when will it run we can never predict.
Upvotes: 1