c - Access to structure member by pointer -
i have structure pass function constant pointer, question following: there difference between 2 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; < 200; i++) { buffer[i] = pt_int[i]; } pt_int = (int*)context->spec3; for(i = 0; < 500; i++) { buffer[i] = pt_int[i]; } ... } void updatefields_2(t_product const* context) { int i,buffer[1500]; for(i = 0; < 200; i++) { buffer[i] = context->spec1[i]; } for(i = 0; < 500; i++) { buffer[i] = context->spec3[i]; } ... } int main(void) { t_product prod; /* initialisation of structure */ ... updatefield(&prod); } i mean, there advantages use pointer member of struct (pointer arrays) instead of accessing directly member of struture.
it's dumb question don't know if access of struct member "costs" more operations.
it won't ever cost more in case. without optimization. pt_int example worse if don't enable optimizations.
this because context->spec3[i] isn't dereferencing more pointers pt_int[i]. pt_int[i] pointer plus offset, access can written @(ptr_int + 4*i). in context->spec3[i], there 1 more pointer dereferenced, isn't case. spec3 isn't value in context, it's offset context. address access therefore @(context + 2000 + 4*i). there 1 pointer access.
now can wonder if @(context + 2000 + 4*i) costs more @(ptr_int + 4*i). doesn't, because architectures, including x86, amd64 , arm (that is, 100% of personal devices), have instructions accesses constant offsets. also, difference can disappear @ enable trivial optimizations, because context + 2000 can converted single context_2000 (but compilers won't that, since can worsen performances).
Comments
Post a Comment