Jump to content
  • Advertisement
Sign in to follow this  
FPSInsanity

Simple Zero Mem Operation

This topic is 4835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi. I just need the most efficient way to set an entire array to zero, or clear out its memory. Right now I'm using a for loop, but I know there must be a much faster way out there. For example: char Array[256]; for( int X = 0; X < 256; X++ ) Array[X] = 0; This seems terribly inefficient, I just need a way to clear the memory. Basically I just need the specifics. I'm using C++.net. If there is a zeromem or function something of the like, what is the name of it and what are the parameters? Thanks for the help.

Share this post


Link to post
Share on other sites
Advertisement
Assuming by C++.net you mean MSVC .NET then you can try memset(), ZeroMemory() or even std::fill() or std::fill_n().

Share this post


Link to post
Share on other sites
I prefer using ZeroMemory(...), but tt doesent matter, since in release mode your code would look something like this:

Release assembly output for "for(int X = 0; X < 256; X++) Array[X] = 0;" is:



; 18 : for(int X = 0; X < 256; X++)
; 19 : {
; 20 : Array[X] = 0;

xor eax, eax
mov ecx, 256 ; 00000100H
lea edi, DWORD PTR _Array$[esp+1032]
rep stosd

; 21 : };

Share this post


Link to post
Share on other sites
Most efficient way is not to zero at all :) Don't laugh, e.g. z-buffer or chess transposition table can just be marked as invalid.
Failing that, use "block prefetch" and movntq - much faster than stosd for large arrays.

Share this post


Link to post
Share on other sites
If you partially initialize an array the compiler sets the remaining elements to zero. Just initialise the first element explicitly to zero then let the compiler initialise the rest e.g.

long totals[500] = {0};

Hope that helps!

Share this post


Link to post
Share on other sites
Quote:
Original post by Cacks
If you partially initialize an array the compiler sets the remaining elements to zero. Just initialise the first element explicitly to zero then let the compiler initialise the rest e.g.

long totals[500] = {0};

Hope that helps!


Tricky!!! I always learn something! [smile]

Share this post


Link to post
Share on other sites
You needn't even explicitly initialize the first element; the following correctly zero-initializes the whole array:
int foo[100] = {};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!