C - fastest method to swap two memory blocks of equal size?

前端 未结 9 2568
春和景丽
春和景丽 2021-02-20 05:20

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

9条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-20 06:03

    Obviously, you have to copy A to Temp, copy B to A, then copy Temp to B. You can do this all at once, for a small area, or do it in sections for a larger area, where you don't want to allocate such a large Temp value. The choice of section size is up to you, though consideration of alignment and cache issues appropriate for the hardware is important, for large, frequent moves.

    (Well, actually there is another way, which doesn't require any temp space: XOR A with B, then XOR B with A, then XOR A with B. An old assembly programmer's trick.)

提交回复
热议问题