aspose file tools*
The moose likes Performance and the fly likes Quick way of clearing array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Quick way of clearing array" Watch "Quick way of clearing array" New topic
Author

Quick way of clearing array

Dave Smith
Greenhorn

Joined: Jan 12, 2000
Posts: 23
This is a routine that is called alot to clear a buffer used to load a file. Could someone tell me how to clear a char array without clearing it one element at a time.
Cheers
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20693
    ∞

See the "Arrays" class. Look for the "fill" method. Of course, it will clear each array element.
I'll usually do something like track how many I want to use in the array so I don't have to worry about clearing the array.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Jack Shirazi
Author
Ranch Hand

Joined: Oct 26, 2000
Posts: 96
Java does not have any memory manipulation operators like C's memset which would allow the array to be cleared in one operation (well, almost none). Instead, if you really have to clear the array, you have to clear each element individually (which is what the "Arrays" method does). For some VMs, keeping a reference emptied array of the same size and using System.arraycopy() might be faster. Theoretically, a VM can implement System.arraycopy() as a memcpy command, and even generate that in native-code to make the copy as fast as possible. In practice System.arraycopy() usually seems to be impemented as a simple loop.
But Paul's second answer is dead on. Why bother to clear the array. Just fill it with the new chunk, but keep a record of how much has been filled and don't operate on elements past the top filled index. Many of the Java collection objects use exactly this mode of operation - see the Vector class implementation for example. This is faster than the fastest possible memory clearing method you could have, because you avoid the operation completely.
 
 
subject: Quick way of clearing array