Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Quick way of clearing array

 
Dave Smith
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21384
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jack Shirazi
Author
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic