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

前端 未结 9 2544
春和景丽
春和景丽 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:07

    The speed for this will be partly platform dependent and only really borne out by testing.

    Personally I'd favour creating a memory block of equal size to one of the arrays; use memcpy to swap the contents around, using the newly created memory block as swap space.

    Now the size of the memory block will have an impact on the speed of operation (again platform dependent) and so you may find that for very large arrays swapping smaller amounts of data back and forth is faster than swapping a large chunk each time.

    edit

    In light of the comment let me explain, my last comment about swapping smaller amounts of data.

    Your aim is to transfer a data to b and b data to a using a temporary swap space tmp.

    The size of tmp is equal to or less than the size of a or b and the number of iterations of swapping data increases as the size of tmp is reduced e.g. if tmp is a 10th of the a then 10 iterations will be needed.

    Now in order to aid the speed of memcpy it is best to ensure that the arrays (a, b and tmp) are allocated aligned memory space.

提交回复
热议问题