Say I have a structure like this:
struct tmp {
unsigned char arr1[10];
unsigned char arr2[10];
int i1;
int i2;
unsigned char arr3[10];
unsigned char arr4[10];
};
Which of these would be faster?
(1) Memset entire struct to 0 and then fill members as:
struct tmp t1;
memset(&t1, 0, sizeof(struct tmp));
t1.i1 = 10;
t1.i2 = 20;
memcpy(t1.arr1, "ab", sizeof("ab"));
// arr2, arr3 and arr4 will be filled later.
OR
(2) Memset separate variables:
struct tmp t1;
t1.i1 = 10;
t1.i2 = 20;
memcpy(t1.arr1, "ab", sizeof("ab"));
memset(t1.arr2, 0, sizeof(t1.arr2); // will be filled later
memset(t2.arr3, 0, sizeof(t1.arr3); // will be filled later
memset(t2.arr4, 0, sizeof(t1.arr4); // will be filled later
Just in terms of performance, is multiple calls to memset faster (on separate members of a structure) faster/slower than a single call to memset (on the entire structure).
t1.arr[0] = '\0';. If the memory image is saved, a global memset is need for alignment of field offsets, where otherwise garbage would be shown..sizeof("ab")counts the null terminator thoughstruct tmp t1 = { .i1 = 10, .i2 = 20, .arr1 = { 'a', 'b' } };. Most compilers would then place t1 in an initialized data section.