Which way of arranging fields in structure is better?

一曲冷凌霜 提交于 2020-01-15 09:47:35

问题


I have two ways to arrange the fields in a structure

  struct foo {  
    float   a;
    double  b;
    float   c;
    double  d;
    short   e;
    long    f;
    short   g;
    long    h;
    char    i;
    int     j;
    char    k;
    int     l;
  };




  struct foo {  
    double  b;
    double  d;
    long    f;
    long    h;
    float   a;
    float   c;
    int     j;
    int     l;
    short   e;
    short   g;
    char    i;
    char    k;
  };

Which one should be practiced and why?


回答1:


The best way to arrange members of a structure is to put them in increasing order, by their size. Doing this, you reduce the padding, required for data alignment.

Also, using some preprocessor directives you modify the alignment, for example:

#define packed_data __attribute__((__packed__))

turns it off. Using this, the member order doesen't matter anymore, but I strongly discourage this, as the memory alingnment is optimised for performance.




回答2:


The Second arrangement is preferable.

In structs, to minimise the loss of bit storage due to padding

(the boundary alignment of various variables in the memory) , it is preferable to start

the structure with variables of the largest size. Go from higher to lower size.

  1. See Padding in structures

  2. Size of variable types in C

    (http://www.cquestions.com/2011/02/size-of-data-types-in-c.html)




回答3:


One sensible way of ordering fields is by their similarity of purpose. For instance:

struct window {
    MENU   *menu ;
    int    width ;
    char   *name ;
    WINDOW *child ;
    int    xpos ;
    int    height ;
    void   *info ;
    WINDOW *next ;
    CLASS  *class ;
    int    ypos ;
    WINDOW *parent ;
    }

would look better as

struct window {
    CLASS  *class ;
    void   *info ;
    char   *name ;
    int    xpos ;
    int    ypos ;
    int    width ;
    int    height ;
    WINDOW *parent ;
    WINDOW *next ;
    WINDOW *child ;
    MENU   *menu ;
    }



回答4:


Padding is one reason to favor one arrangement over another. Another option is to sort the fields by their frequency or by their memory access pattern. This is of course micro-optimization, but it can pay off in extreme cases.

Many, or most CPU architectures encode smaller offsets in pointers with smaller opcodes; Putting the most frequently accessed element to offset zero can in especially RISC architectures reduce the number of instructions, as well as make the code run faster.

If 'x' is used at the same time as 'y', it's beneficial to put them in the same cache line instead of face the risk of two or more cache misses per structure.



来源:https://stackoverflow.com/questions/20018935/which-way-of-arranging-fields-in-structure-is-better

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!