c - Better to pass struct, or pointer to struct? -
i have data struct, read in function.
i want smallest memory, code size, , speed footprint possible. i'm working on avr.
typedef struct { uint16_t clu; uint16_t num; uint32_t cur_rel; } fsavepos; now, function stores file position struct:
// approach 1 fsavepos save_pos(const ffile* file); // return value // approach 2 void save_pos(const ffile* file, fsavepos* pos); // modify reference and function reverses (ffile object modified):
// approach 1 void restore_pos(ffile* file, const fsavepos pos); // pass value // approach 2 void restore_pos(ffile* file, const fsavepos* pos); // pass reference what advise best idea?
if trying minimise memory footprint, struct type larger pointer better passed using pointer. data smaller better passed value. if pointer , data same size, doesn't matter much.
assuming on avr32, pointer 32-bit , struct 64-bit (plus padding).
that suggest better passing pointer/reference. however, struct not particularly large, other considerations may dominate - there not lot in struct type, not particularly large. need measure relevant quantities (memory usage, code size, speed, etc) sure.
so best idea, suggest, measure - these things affected host architecture, compiler settings, quality of implementation of compiler, etc.
although haven't asked, larger types (like uint32_t) tend have larger alignment requirements smaller types (like uint16_t). consequence of common guideline of ordering members of struct larger types appear first in memory. not significant in case either (it fair bet 16 bit type aligned 16 bit boundaries, , 32-bit types 32-bit boundaries, there no padding in case). however, if had 3 uint16_t members rather two, better off ordering things uint32_t members first. in other words, instead of
typedef struct { uint16_t a,b,c; uint32_t d; } some_type; you better off using different order.
typedef struct { uint32_t d; uint16_t a,b,c; } some_type;
Comments
Post a Comment