From: http://blog.codingnow.com/2005/10/vc_memcpy.html
In many compilers, memcpy is an intrinsic function, that is, this function is implemented by the compiler. It is easier to be optimized during compilation than the inline function. The compiler can make multiple versions based on whether the memcpy parameter is a constant or a variable to achieve optimal performance. This cannot be done using inline or template.
Let's take a look at the optimization of memcpy by VC. (Vc6)
Void Foo (void * D, const void * s)
{
Memcpy (D, S, 1 );
}
Select performance optimization to generate an assemblyCodeYou can see. The code is optimized:
MoV eax, dword ptr _ S $ [esp-4]
MoV edX, dword ptr _ d $ [esp-4]
MoV Cl, byte PTR [eax]
MoV byte PTR [edX], Cl
Only one byte copy is completed using the CL register mov.
After 1 is changed to 4:
MoV eax, dword ptr _ S $ [esp-4]
MoV edX, dword ptr _ d $ [esp-4]
MoV ECx, dword ptr [eax]
MoV dword ptr [edX], ECx
It becomes the most common mov command.
If it is 8 Bytes:
MoV eax, dword ptr _ S $ [esp-4]
MoV ECx, dword ptr _ d $ [esp-4]
MoV edX, dword ptr [eax]
MoV dword ptr [ECx], EDX
MoV eax, dword ptr [eax + 4]
MoV dword ptr [ECx + 4], eax
It is two mov commands.
Until the length is constant 19 or completed with MoV:
MoV eax, dword ptr _ S $ [esp-4]
MoV ECx, dword ptr _ d $ [esp-4]
MoV edX, dword ptr [eax]
MoV dword ptr [ECx], EDX
MoV edX, dword ptr [eax + 4]
MoV dword ptr [ECx + 4], EDX
MoV edX, dword ptr [eax + 8]
MoV dword ptr [ECx + 8], EDX
MoV edX, dword ptr [eax + 12]
MoV dword ptr [ECx + 12], EDX
MoV dx, word PTR [eax + 16]
MoV word PTR [ECx + 16], DX
MoV Al, byte PTR [eax + 18]
MoV byte PTR [ECx + 18], Al
After the length reaches 20, it becomes the use of rep movsd
Push ESI
MoV ESI, dword ptr _ S $ [esp]
Push EDI
MoV EDI, dword ptr _ d $ [esp + 4]
MoV ECx, 5
Rep movsd
Pop EDI
Pop ESI
If the length is not an integer multiple of 4, for example, copying 23 Bytes:
Push ESI
MoV ESI, dword ptr _ S $ [esp]
Push EDI
MoV EDI, dword ptr _ d $ [esp + 4]
MoV ECx, 5
Rep movsd
Movsw
Movsb
Pop EDI
Pop ESI
The compiler inserts movsw and movsb.
Now let's take a look at the length of memcpy as a variable:
Void Foo (void * D, const void * s, size_t size)
{
Memcpy (D, S, size );
}
This time, the compiler directly calls rep movsd.
MoV ECx, dword ptr _ SIZE $ [esp-4]
Push ESI
MoV ESI, dword ptr _ S $ [esp]
MoV eax, ECx
Push EDI
MoV EDI, dword ptr _ d $ [esp + 4]
SHR ECx, 2
Rep movsd
MoV ECx, eax
And ECx, 3
Rep movsb
Pop EDI
Pop ESI
Because we don't know whether the size is an integer multiple of 4, we processed it with and ECx, 3/repmovsb on the tail.
Can we notify the compiler that the data block length of memcpy is a multiple of 4? The answer is yes. Let's see how the compiler compiles memcpy (D, S, size * 4 );
MoV ECx, dword ptr _ SIZE $ [esp-4]
Push ESI
MoV ESI, dword ptr _ S $ [esp]
Push EDI
MoV EDI, dword ptr _ d $ [esp + 4]
Rep movsd
Pop EDI
Pop ESI
Very concise, isn't it?