> -----Original Message-----
> From: Vamsi_K [mailto:Vamsi_K@Satyam.com]
> Sent: Wednesday, May 04, 2005 11:23 AM
> To: Vijay Zanvar (WT01 - TELECOM SOLUTIONS)
> Subject: Hii...Small Query
>
>
> Hi Vijay,
>
> Can u please tell me the difference between strcpy() and memcpy().
> How memcpy() is faster for Large strings, eventhough there are 2 passes
> over the data.
>
> Ie, one for strlen() and another is for copying.
> Please give me reply if u find any free time.
>
Following are the prototypes of memcpy() and strcpy().
#include <string.h>
void *memcpy(void * restrict s1, const void * restrict s2,
size_t n);
#include <string.h>
char *strcpy(char * restrict s1, const char * restrict s2);
The effectiveness of memcpy() depends on the two factors:
* How it is implemented, and
* The values of `n' and strlen (s2). (see above prototypes)
It is not always that memcpy() is always faster; however, it is
faster/slower in following situations:
* If strlen(s2) is far greater than `n'
* If you know the exact number of bytes to be copied
in advance, then memcpy() more efficient than strcpy()
* If you use the following method -
memcpy ( s1, s2, strlen(s2) );
- then, it will slower than strcpy().
* If the library implements memcpy() using the fast
instructions, if any, provided by the host processor.
For example, Intel CPUs provide the following instructions
for fast copying:
MOVS/MOVSB/MOVSW/MOVSDāMove Data from String to String
Opcode Instruction Description
------ ----------- -----------
A4 MOVS m8, m8 Move byte at address DS:(E)SI to address ES:(E)DI
A5 MOVS m16, m16 Move word at address DS:(E)SI to address ES:(E)DI
A5 MOVS m32, m32 Move doubleword at address DS:(E)SI to address ES:(E)DI
A4 MOVSB Move byte at address DS:(E)SI to address ES:(E)DI
A5 MOVSW Move word at address DS:(E)SI to address ES:(E)DI
A5 MOVSD Move doubleword at address DS:(E)SI to address ES:(E)DI
An simple implementation could be like this:
char *
strcpy ( char * restrict s1, const char * restrict s2 )
{
/*
* I didn't cross check the syntax of __asm.
* Refer "info gcc" for more information
*/
__asm ( "MOVS s1, s2" );
return s1;
}
However, It is advisable to use str functions for manipulating
strings, instead of using mem functions. Because, that will
improve readability.
> Thanks & Regards
> Vamsi Krishna.K