I have a structure that I pass to a function as constant pointer, my question is the following: There is a difference between those two implementations of function updatedFields:
typedef struct
{
int spec[100];
int spec1[200];
int spec2[200];
int spec3[500];
int spec4[100];
int spec5[700];
float value[100];
char desc[1000]:
}t_product;
void updateFields_1(t_product const* context)
{
int i,buffer[1500];
int * pt_int;
pt_int = (int*)context->spec1;
for(i = 0; i < 200; i++)
{
buffer[i] = pt_int[i];
}
pt_int = (int*)context->spec3;
for(i = 0; i < 500; i++)
{
buffer[i] = pt_int[i];
}
...
}
void updateFields_2(t_product const* context)
{
int i,buffer[1500];
for(i = 0; i < 200; i++)
{
buffer[i] = context->spec1[i];
}
for(i = 0; i < 500; i++)
{
buffer[i] = context->spec3[i];
}
...
}
int main(void)
{
t_product prod;
/* Initialisation of the structure */
...
updateField(&prod);
}
I mean, there is any advantages to use pointer to member of a struct (pointer to the arrays) instead of accessing directly to the member of struture.
It's probably a dumb question but I don't know if the access of a struct member "costs" more operations.
It won't ever cost more in your case. Even without optimization. Actually your pt_int example is likely to be slightly worse if you don't enable optimizations.
This is because context->spec3[i] isn't dereferencing more pointers than pt_int[i]. pt_int[i] is just a pointer plus an offset, so the access can be written as @(ptr_int + 4*i). In context->spec3[i], it could look like there is one more pointer dereferenced, but it isn't the case. spec3 isn't a value in context, it's just an offset from context. The address you access will therefore be @(context + 2000 + 4*i). There is only one pointer access.
Now you can wonder if @(context + 2000 + 4*i) costs more than @(ptr_int + 4*i). It doesn't, because most architectures, including x86, AMD64 and ARM (that is, 100% of personal devices), have instructions to do accesses with constant offsets. Also, the difference can disappear at soon as you enable trivial optimizations, because context + 2000 can be converted to a single context_2000 (but compilers won't actually do that, since it can only worsen performances).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With