What is the reason for aligning to 8?

  struct {              /* Fileheader */
    uchar file_version[4];
    uchar options[2];
    uchar header_length[2];
    uchar state_info_length[2];
    uchar base_info_length[2];
    uchar base_pos[2];
    uchar key_parts[2];         /* Key parts */
    uchar unique_key_parts[2];      /* Key parts + unique parts */
    uchar keys;             /* number of keys in file */
    uchar uniques;          /* number of UNIQUE definitions */
    uchar language;         /* Language for indexes */
    uchar max_block_size_index;     /* max keyblock size */
    uchar fulltext_keys;
    uchar not_used;                     /* To align to 8 */
  } header;

The above is extracted from a MySQL source,

why set alignment by 8?

+5
source share
3 answers

This is an optimization that provides more efficient access to structures in the CPU memory.

http://en.wikipedia.org/wiki/Data_structure_alignment

+6
source

Reason 1: Address calculations are faster and less.

x86, , , " ". ", " x86. :

struct s { char c[N]; };
int func(struct s *p, int i) { return p[i].c[0]; }

N 23 ( ):

leaq    (%rsi,%rsi,2), %rax
salq    $3, %rax
subq    %rsi, %rax
movsbl  (%rax,%rdi),%eax

N 24 ( ):

leaq    (%rsi,%rsi,2), %rax
movsbl  (%rdi,%rax,8),%eax

N 32 ( ):

salq    $5, %rsi
movsbl  (%rsi,%rdi),%eax

, 23- .

2:. .

, . 32- . - , . , .

unsigned char *data = ...;
header *h = (header *) data;
do_something_with(h);
uint32_t x = *(uint32_t *) (data + sizeof(header));

SPARC, sizeof(header) 4, x86 , sizeof(header) 4.

+3

, . . /​​ , .

Dani, , , , file_version, uint32_t, .

Some code

#include <stdio.h>

struct padded {
    unsigned char file_version[4];
    unsigned char options[2];
    unsigned char header_length[2];
    unsigned char state_info_length[2];
    unsigned char base_info_length[2];
    unsigned char base_pos[2];
    unsigned char key_parts[2];
    unsigned char unique_key_parts[2];
    unsigned char keys;
    unsigned char uniques;
    unsigned char language;
    unsigned char max_block_size_index;
    unsigned char fulltext_keys;
    unsigned char not_used;
};

struct unpadded {
    unsigned char file_version[4];
    unsigned char options[2];
    unsigned char header_length[2];
    unsigned char state_info_length[2];
    unsigned char base_info_length[2];
    unsigned char base_pos[2];
    unsigned char key_parts[2];
    unsigned char unique_key_parts[2];
    unsigned char keys;
    unsigned char uniques;
    unsigned char language;
    unsigned char max_block_size_index;
    unsigned char fulltext_keys;
};

int main() {
    printf("size padded:      %lu\n", sizeof(struct padded));
    printf("size unpadded:    %lu\n", sizeof(struct unpadded));

    printf("size padded[2]:   %lu\n", sizeof(struct padded[2]));
    printf("size unpadded[2]: %lu\n", sizeof(struct unpadded[2]));
}

Output

size padded:      24
size unpadded:    23
size padded[2]:   48
size unpadded[2]: 46
+1
source

All Articles