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

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

    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.

提交回复
热议问题