Campus Ambassador Coordinator Around the Sun

Monday Jun 02, 2008

Something  I learned today on my Advanced Crash Dump Analysis course that I've never thought about before was how we can improve the performance of our programs just by re-ordering our variables in data structures. Whenever you write something like the following in C you naturally use up memory:

	struct unpacked {

int a; char b; int c; char d; int e;

};

The above structure (we can assume), will use up 20 bytes of memory due to the padding. This is due to the way the structure is layed out in memory. Assuming that we're using a Intel processor and that we are storing our values in memory in multiples of the sizeof() the item we're storing, if we were to look at the memory layout for the above struct we'd expect to see something like the following:

  int a
 int a
  int a
 int a
 char b
pad
pad
 pad 
 int c
int c
 int c
int c
 char d
 pad
 pad
pad
 int e
int e
 int e
int e

However, assume this time that we program the struct as follows:

	struct packed {

		int a, c, e;
		char b, d;

	};

Well, now we've reduced the amount of space used to 16 bytes - and no it's not because I've removed those line breaks! Instead of wasted space in memory between those ints and chars we're using the space more wisely. The new layout in memory would be something like the following:

 int a
 int a
 int a
 int a
 int c
 int c
 int c
 int c
 int e
 int e
 int e
 int e
 char b
 char d
 pad
 pad
 free free
free
free

Naturally there will be instances where you don't really have much choice how you order your structs - especially when dealing with hardware or predefined protocols by other people or organisations. Indeed, the performance gains may not even be that big - but it just peaked my interest and so I thought I'd share it with you :)

Comments:

Oh!

Fantastic tip !
Just goes to show how good programing practice and understanding can improve a particular application you maybe working on in so many obscure ways.

Thanks for this, and I hope you can share some more hints if you ever get a moment,
Edward.

Posted by EdwardOCallaghan on June 03, 2008 at 04:08 AM BST #

Post a Comment:
  • HTML Syntax: NOT allowed