-
Memory usage and array allocation
I have an array called myNums that is initialized with several elements, then later in the program the elements get changed.
At some point I need to reset it to its original condition, which is more efficient? (I know at this size it is trivial but it is the concept I am aiming for.)
for (int i = 0 ; i < 10 ; i++){
myNums[i] = i+1;
}
or
myNums = new int[] {1,2,3,4,5,6,7,8,9};
I wasn't sure if creating the new anonymous array was bad for memory or efficiency.
Thanks!
-
Because Java is going to clean up any memory that is no longer used, it probably isn't that big of a deal. The thing that you should look at is anything that might have a reference to that array to make sure that it will be cleaned up. If you have stray references then modifying the array may have undesired affects in your program, but resetting the reference will just add more memory. Generally, memory operations shouldn't be a big deal when the allocation is small, but if this array is going to be expensive to the point that having 2 instances of it around simultaneously + extra memory for the program could trigger actually allocating more memory (as opposed to just getting it from recycled memory) I would reinitialize it with the loop, otherwise, its not a big deal.
~evlich
-
Just a couple of remarks. If the arry contains non-objects (int, float etc.) you need
not worry about references getting "lost" when you reset its contents.
If the array containes object that has a reset() method you also needen't worry.
However, if myNums is a class global variable and other classes reference it using
copies of its reference, then your second method (using new) will invalidate those
references as the new array will be reallocated, i.e. get new reference (memory
location).
The problem concering efficiency is is my opinion (almost) purely academical, it should
not be adressed unless you are dealing with monster arrays or loops doing this thousands of times.
As for java's garbage handling, this is not instantaneous, it is
not done at the very same moment no other references exist to an object.
Check the doc for System.gc().
eschew obfuscation
-
Thanks! That clears up a few concerns.
Similar Threads
-
By Patrick Ireland in forum .NET
Replies: 4
Last Post: 07-24-2001, 04:44 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks