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-tim
You could use the logic described here. This way, you could save a third buffer.
#include
#include
void swap(uint8_t *a, uint8_t *b, size_t length) {
size_t i;
for (i=0; i
Even only this one temporary variable is enough to help the compiler optimize this.
But if you use such a temporary variable, you can do as well
#include
#include
void swap(uint8_t *a, uint8_t *b, size_t length) {
size_t i;
for (i=0; i
In the first glance, both of them look expensive due to the many array accesses (in the 1st case) and the processing of only one byte per loop run, but if you let your compiler optimize this, it should be ok, as (at least gcc) is smart enough to bundle always 4 steps (in x64: even 16 steps) into one loop run.
Note that your compiler might not optimize so aggressively, so you might have to do the said splitting by yourself. In this case, take care about the alignment.