4.4.3 CopyMem() and SetMem() Operations

The following example shows how to use the EDK II library BaseMemoryLib functions CopyMem() and SetMem()to improve the performance of a UEFI driver. These techniques apply to arrays, structures, or allocated buffers.

Note: By default, the EDK II enables high levels of optimization, so this example may not build for all compilers because the loops are optimized into intrinsics that can cause the link to fail. So not only does use of 'CopyMem()' and 'SetMem()' improve performance, it also improves UEFI Driver portability.

Example 15-CopyMem() and SetMem() Speed Optimizations

#include <Uefi.h>
typedef struct {
UINT8 First;
UINT32 Second;
} MY_STRUCTURE;
UINTN Index;
UINT8 A[100];
UINT8 B[100];
MY_STRUCTURE MyStructureA;
MY_STRUCTURE MyStructureB;
//
// Using a loop is slow or structure assignments is slow
//
for (Index = 0; Index < 100; Index++) {
A[Index] = B[Index];
}
MyStructureA = MyStructureB;
//
// Using the optimized CopyMem() Boot Services is fast
//
CopyMem (
(VOID *)A,
(VOID *)B,
100
);
CopyMem (
(VOID *)&MyStructureA,
(VOID *)&MyStructureB,
sizeof (MY_STRUCTURE)
);
//
// Using a loop or individual assignment statements is slow
//
for (Index = 0; Index < 100; Index++) {
A[Index] = 0;
}
MyStructureA.First = 0;
MyStructureA.Second = 0;
//
// Using the optimized SetMem() Boot Service is fast.
//
SetMem ((VOID *)A, 100, 0);
SetMem ((VOID *)&MyStructureA, sizeof (MY_STRUCTURE), 0);