What is the fastest way to swap two non-overlapping memory areas of equal size? Say, I need to swap (t_Some *a)
with (t_Some *b)
. Considering space-time trade-off, will increased temporary space improve the speed? For example, (char *tmp)
vs (int *tmp)
? I am looking for a portable solution.
Prototype:
void swap_elements_of_array(void* base, size_t size_of_element, int a, int b);
Your best bet is to maximize registers usage so that when you read a temporary you don't end up with extra (likely cached) memory accesses. Number of registers will depend on a system and registers allocation (the logic that maps your variables onto actual registers) will depend on a compiler. So your best bet is I guess to expect only one register and expect its size to be the same as the pointer. Which boils down to a simple for-loop dealing with blocks interpreted as arrays of size_t
.