1

Why it is said to keep very frequently used variables always at the top of the structure. I know it is something to do with performance. But If someone explains in detail or give a URL hit, would be very much appreciated.

Whoami
  • 13,930
  • 19
  • 84
  • 140
  • My guess is, that you are asking about the struct memory layout. [Please look at his question for a detailed answer](http://stackoverflow.com/questions/2748995/c-struct-memory-layout) – Jesse Good Dec 12 '11 at 06:42
  • @Jesse, Thanks for the link. But What i was looking for is not the structure memory layout, but about the **performance impact** over memory layout. – Whoami Dec 12 '11 at 07:00

3 Answers3

3

A member in a structure is normally accessed by the compiler by having a base address, and then adding an offset to get the member. Some (especially older) CPU architectures could not use large offsets, so if the structure was large or contained arrays it would have used slower access methods. On modern CPU architectures and using modern compilers (and with modern I mean like the last 10-15 years which in computer history is pretty ancient) it should not be a problem.

The only time you should need to think about your structure layout today, is if you are building for minimal embedded systems, where you might want to save every byte of memory. Not because of access performance, but because to minimize padding between members.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Perhaps you want to keep frequently used member data fields together because of cache issues (i.e. hoping that they fit in the same cache line). But I am not sure it matters that much.

See also this reply about __builtin_prefetch with GCC on Linux.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

edit: I was wrong about my answer, there is difference.

Problem is that sizeof these structs may be different:

#include <stdio.h>

main()
{
        struct {
        char a;
        char b;
        int i;
        }A;

        struct{
        char a;
        int i;
        char b;
        }B;

        printf("%d %d",sizeof(A), sizeof(B));

        return 0;
}

While first is typically 8Bytes ( 2*sizeof(char)+ sizeof(int) = 6 .. rest gets rounded to final 8bytes), second may be even 12 Bytes long (x86 align by factor of 4).

This is done not to mess indexation within structure and it cannot be optimized (feature of language, element order within struct is fixed!).

For more check latest version of standard (C11) and "Alignment specification (_Alignas specifier, alignof operator, aligned_alloc function, header file)".

Tomas Pruzina
  • 8,397
  • 6
  • 26
  • 39