memset/memcpy

Started by
12 comments, last by Jan Wassenberg 18 years, 4 months ago
are these functions actually faster than doing it manually? I mean is memset(array,0,sizeof(array)) rly faster than setting everything in the array to 0 in a for loop? and memcpy(&array1,&array2,sizeof(array2)) faster than looping through and copying values over?
Advertisement
yes it is really faster. but if you're skeptical just write a little test app where you initialize a huge array both ways and time the different solutions.

-me
If you're using C++, look into std::copy and std::fill. If you're using C, probably best to stick with them.
Moved to General Programming.
memset/memcpy are likely to be the most efficient possible setting/copying implementation on your system, so the best a for loop will ever do is a draw. That wasn't always true thought, when Michael Abrash was working on Quake he found that the memcpy they had was a byte-by-byte copy which he beat easily.
sorry, I didnt see a C++ section so I just put it in directX.
thx
wait, when you say he beat it.... does that mean its possible to write a memcpy function thats faster than memcpy?
Probably not these days. Once upon a time it was possible.
On MSVC++ 2003, memset doesn't even perform a proper function call - a short assembly routine is inserted inline, which uses "rep stosd" to zero memory, a dword at a time.

Having said that, you _can_ beat it by using the FPU to fill 4 words at a time, or SSE to fill 8 words at a time.
You should always prefer a standard library call to do these sorts of things, because that call provides more useful information to the compiler. The compiler can more easily be written to detect "oh, that's a function call that I have a builtin superfast replacement for" than "oh, that loop is *really* just doing X which I have a builtin superfast replacement for".

In C++, std::copy/std::fill should be used because (a) it provides the above sort of information (and further, template magic can be used to make it use different 'superfast replacements' depending on the types of data involved) and (b) it will *not* do "superfast replacements" - or even nearly-as-fast manual scribbling over memory - in cases where it is not safe to do so (e.g. with an array of non-POD types).

This topic is closed to new replies.

Advertisement