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

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

    Word writes will be the fastest. However, both block size and alignment need to be considered. In practice things are usually aligned sensibly, but you shouldn't count on it. memcpy() safely handles everything and may be specialized (built-in) for constant sizes within reason.

    Here is a portable solution that works reasonably well in most cases.

    static void swap_byte(void* a, void* b, size_t count)
    {
        char* x = (char*) a;
        char* y = (char*) b;
    
        while (count--) {
            char t = *x; *x = *y; *y = t;
            x += 1;
            y += 1;
        }
    }
    
    static void swap_word(void* a, void* b, size_t count)
    {
        char* x = (char*) a;
        char* y = (char*) b;
        long t[1];
    
        while (count--) {
            memcpy(t, x, sizeof(long));
            memcpy(x, y, sizeof(long));
            memcpy(y, t, sizeof(long));
            x += sizeof(long);
            y += sizeof(long);
        }
    }
    
    void memswap(void* a, void* b, size_t size)
    {
        size_t words = size / sizeof(long);
        size_t bytes = size % sizeof(long);
        swap_word(a, b, words);
        a = (char*) a + words * sizeof(long);
        b = (char*) b + words * sizeof(long);
        swap_byte(a, b, bytes);
    }
    

提交回复
热议问题