Sequential Structure Layout For Speed


This code will Highlight Wise Choice for layout Structure we are going to declare a Matrix which is used to house a Set.. Explicitly.  Just by putting the iteration value in the middle of the sequence you can speed up that example code by a factor of 36% !.. and that is just by adjusting the location of data in the memory…. !



using System.Runtime.InteropServices;

…..

[StructLayout(LayoutKind.Explicit)]

public class PoorChoice

{

[FieldOffset(0)]

public int i;

[FieldOffset(4)]

public int m00;

[FieldOffset(8)]

public int m01;

[FieldOffset(16)]

public int m02;

[FieldOffset(20)]

public int m03;

[FieldOffset(24)]

public int m10;

[FieldOffset(28)]

public int m11;

[FieldOffset(32)]

public int m12;

[FieldOffset(36)]

public int m13;

[FieldOffset(40)]

public int m20;

[FieldOffset(44)]

public int m21;

[FieldOffset(48)]

public int m22;

[FieldOffset(52)]

public int m23;

[FieldOffset(56)]

public int m30;

[FieldOffset(60)]

public int m31;

[FieldOffset(64)]

public int m32;

[FieldOffset(68)]

public int m33;

}

 

[StructLayout(LayoutKind.Explicit)]

public class GreatChoice

{

[FieldOffset(0)]

public int m00;

[FieldOffset(4)]

public int m01;

[FieldOffset(8)]

public int m02;

[FieldOffset(12)]

public int m03;

[FieldOffset(16)]

public int m10;

[FieldOffset(20)]

public int m11;

[FieldOffset(24)]

public int m12;

[FieldOffset(28)]

public int m13;

[FieldOffset(32)]

public byte i;

[FieldOffset(33)]

public int m20;

[FieldOffset(37)]

public int m21;

[FieldOffset(41)]

public int m22;

[FieldOffset(45)]

public int m23;

[FieldOffset(49)]

public int m30;

[FieldOffset(53)]

public int m31;

[FieldOffset(57)]

public int m32;

[FieldOffset(61)]

public int m33;

}

 

This sample is designed for 32 bit systems, if your running a 64 bit system you will need to double the number of "m" elements keeping the "i" value relatively in the same position (head, middle respectively).

And Here are the results from adding i to the matrix elements… (this was individually timed inside of a for loop  200 times, then a simple average was taken)… Total savings 0.175 seconds! This was pitted against the CLR and CLR results are somewhere in between (as would be expected).

Advertisements

About Larry Louisiana

I'm a Microsoft Partner Consultant.
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s