This week's book giveaway is in the Agile forum.
We're giving away four copies of Fixing your Scrum and have Ryan Ripley & Todd Miller on-line!
See this thread for details.
Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

Quick way of clearing array

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Trailboss
Posts: 23366
IntelliJ IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Author
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic