Post by Hicham MoulineHello,
Are there any articles comparing the cases/reasons when/why to use memset vs
fill, vs writing a loop by hand?
If you want an article, there's always google:
http://stackoverflow.com/questions/1373369/what-is-faster-prefered-memset-or-for-loop-to-zero-out-an-array-of-doubles
It was the second link google gave, the first being your post! Note
the comments on the first answer which state that std::fill and
std::copy are sometimes specialized for POD containers. Theoretically,
i suppose it should make a difference between std::fill and memset.
But...
#include <algorithm>
#include <cstring>
using namespace std;
// Note:
// usingbe = using [begin,end)
// usingbs = using [begin,begin+size)
void usingbe_memset( int* begin, int* end, int value )
{
memset( begin, value, (end-begin)*sizeof(int) );
}
void usingbs_memset( int* begin, size_t size, int value )
{
memset( begin, value, size );
}
void usingbe_fill( int* begin, int* end, int value )
{
std::fill( begin, end, value );
}
void usingbs_fill( int* begin, size_t size, int value )
{
std::fill_n( begin, size, value );
}
void usingbe_loop( int* begin, int* end, int value )
{
while( begin != end )
*(begin++) = value;
}
void usingbs_loop( int* begin, size_t size, int value )
{
while( size-- )
*(begin++) = value;
}
Compiled with g++ version 4.4.1, command line options "-c -O3 -S". ("-
c" removes the need for main().) The assembly, for brevity, i've
posted here: http://pastebin.com/PVUUGGqH
For those who can't read assembly, the code for usingb[se]_memset
neither actually calls memset, nor loops, but instead uses one
instruction, "rep stosb", which i highlighted, that does the job.
However, every other function uses pretty much the exact same loop.
MSVC produced similar results.
So, theoretically, there is no difference and your compiler will
optimize everything; in reality, that is not always true. Since this
seems to go against the general advice, i wonder if either my test is
poorly designed or my compilers just don't do this optimization.
Perhaps there's another compiler option i need enabled.
Other than that, std::fill is more generic than memset since it works
with any type. std::fill is more clear than a for loop because when
you write
for(int i=0; i < LEN; i++ )
a[i] = X;
the meaning of the loop is implied, but not as explicit as
std::fill( a, a+LEN, X );
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]