Copying Data Blocks in memory

Started by
4 comments, last by LonelyStar 20 years, 1 month ago
Hi everybody, If I want to copy Data from one part of the memory into another, I do:

for(int i=0;i<DataBlockSize;i++)
{
  DestData[i]=SrcData[i];
}
and, no wonder, it works. But is there a faster way of doing that? I am looking for an Multi-platform way (Linux & Win32). Thanks!
Advertisement
Use memcpy(), it''s included in every standard library for win, linux, unix etc. See docs for more info.
Probably, depending on the context.

See, if you are copying null terminated strings, you can eliminate a couple of operands like so:
char * x = Src;char * y = Trg;while (x){   *(y++) = *(x++); }

But, theres strcpy() for that, which is probably much much faster. The reason I showed this example is that its just a matter of changing your thinking, so that you use faster operands. When copying objects, you''d just copy relevant data back and forth.
william bubel
I hope you mean:

while (*x)

above.
Yes just use the built-in''s btw. If a hand-written version was faster then wouldn''t they just put that into the std libs?
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Thats like asking why up untill 7.1 STLPort was faster then MS-STL. The STL can (and is) implemented differently for different compilers, as long as it sticks to the specs, its right. The specs dont go into details about the machine language, or optimizations. So for some compilers, your own code is best. In addition, coding your own allows you to make it "feel" the way you want, and provide more power to it.

Edit: MS-STL also wasnt fully to the specs i believe, but it also was known to be slower and more problematic. This may still be true to a point, but most of it was fixed in 7.1

[edited by - paulcesar on March 20, 2004 4:57:33 PM]
> Yes just use the built-in''s btw.
Good advice, unless you''re looking for speed; admittedly, these cases are rare for memcpy and strcpy.

> If a hand-written version was faster then wouldn''t they just put that into the std libs?
Why should they? Does it make business sense to do so?
That aside, there may be faster, but processor-dependent ways of doing something (standard example: sqrt). The standard library has to work on all systems, and sometimes it is more effort to determine if an extension exists than there is gain for using it.

This topic is closed to new replies.

Advertisement