V802. On 32-bit/64-bit platform, structure size can be reduced from N to K bytes by rearranging the fields according to their sizes in decreasing order.


The analyzer detected a construct which can be optimized. There is a data structure in program code that might cause inefficient use of memory.

Let's examine a sample of such a structure the analyzer considers inefficient:

struct LiseElement {
  bool m_isActive;
  char *m_pNext;
  int m_value;
};

This structure occupies 24 bytes in 64-bit code because of data alignment. But if you change the field sequence, its size will be only 16 bytes. This is the optimized structure:

struct LiseElement {
  char *m_pNext;
  int m_value;
  bool m_isActive;
};

Of course, field rearrangement is not always possible or necessary. But if you use millions of such structures, it is reasonable to optimize memory being consumed. Additional reduction of structures' sizes may increase the application's performance because fewer memory accesses will be needed at the same number of items.

Note that the structure described above always occupies 12 bytes in a 32-bit program regardless of the field sequence. That is why the V802 message will not be shown when checking the 32-bit configuration.

Surely there might be opposite cases when you can optimize a structure's size in the 32-bit configuration and cannot do that in the 64-bit configuration. Here is a sample of such a structure:

struct T_2
{
  int *m_p1;
  __int64 m_x;
  int *m_p2;
}

This structure occupies 24 bytes in the 32-bit program because of the alignment. If we rearrange the fields as shown below, its size will be only 16 bytes.

struct T_2
{
  __int64 m_x;
  int *m_p1;
  int *m_p2;
}

It does not matter how fields are arranged in the 'T_2' structure in the 64-bit configuration: it will occupy 24 bytes anyway.

The method of reducing structures' sizes is rather simple. You just need to arrange fields in descending order of their sizes. In this case, fields will be arranged without unnecessary gaps. For instance, take this structure of 40 bytes in a 64-bit program:

struct MyStruct
{
  int m_int;
  size_t m_size_t;
  short m_short;
  void *m_ptr;
  char m_char;
};

By simply sorting the sequence of fields in descending order of their sizes:

struct MyStructOpt
{
  void *m_ptr;
  size_t m_size_t;
  int m_int;
  short m_short;
  char m_char;
};

we get a structure with the size of 24 bytes.

The analyzer does not always generate messages about inefficient structures because it tries to make unnecessary warnings fewer. For instance, the analyzer does not generate this warning for complex descendant classes since there are usually rather few of such objects. For example:

class MyWindow : public CWnd {
  bool m_isActive;
  size_t m_sizeX, m_sizeY;
  char m_color[3];
  ...
};

This structure's size may be reduced but it does not give your practical benefit.