Search code examples
cmemcpy

Data copy method direct assign vs memcpy in c


I want to copy data from different variables and put it together in an array so that I can process it further.

I have studied direct assignment and memcpy method and think memcpy is used to copy complete buffer and not individual elements. Also I think it may take time and waste CPU cycles to use memcpy for individual bytes.

Can you please let me know from below example what should be used in such case since it is running in multithreaded environment(different example) and varibles may change?

#include <stdio.h>
#include <stdint.h>

int main()
{

    printf("Direct assign method\n");

    uint8_t pack_id = 123;
    uint8_t pack_age = 76;
    uint8_t pack_cmd = 30;

    uint8_t cus_data[3] = {0};

    cus_data[0] = pack_id;
    cus_data[1] = pack_age;
    cus_data[2] = pack_cmd;

    printf("Memcpy method\n");

    pack_id = 112;
    pack_age = 89;
    pack_cmd = 25;

    memcpy(&cus_data[0], &pack_id, sizeof(pack_id));
    memcpy(&cus_data[1], &pack_age, sizeof(pack_age));
    memcpy(&cus_data[2], &pack_cmd, sizeof(pack_cmd));

    return 0;
}

Solution

  • cus_data[0] = pack_id; is never slower than memcpy(&cus_data[0], &pack_id, sizeof(pack_id));. They may however be equally fast, if the compiler inlines the memcpy call, which is very likely.

    What you should do instead of worrying about micro-optimizations is to write the most readable code possible. Worry about optimizations when you encounter actual performance problems.

    Since cus_data[0] = pack_id; is the most readable, that's what you should be doing.


    in such case since it is running in multithreaded environment

    Doesn't make a difference. Either you need to protect the variables against re-entrancy bugs, or you don't need to protect them. This has nothing to do with simple assignment vs memcpy, because neither of them are guaranteed to be atomic.

    It doesn't matter how small/large the variables are, since nothing in the C language guarantees atomic access unless you use C11 _Atomic and similar.