Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Optimize class member layout needed? (Byte padding)

Status
Not open for further replies.

Sypher2

Programmer
Oct 3, 2001
160
US
In Visual Basic .NET is it necessary to pay attention to the layout of member variables? I know in C++ the order in which you declare your variable can have an affect on the amount of RAM used. This is because of byte alignment and padding.

Example:
Code:
[blue]Dim[/blue] b [blue]As[/blue] Byte  [green]'1 byte[/green]
[blue]Dim[/blue] i [blue]As[/blue] Int32 [green]'4 bytes[/green]
[blue]Dim[/blue] s [blue]As[/blue] Int16 [green]'2 bytes[/green]
Usually variables are aligned in memory in 4 byte segments. In the above example the first variable "b" takes up 1 byte. Since the second variable "i" is 4 bytes, it cannot fit in the same block as "b". So "b" is padded with an additional 3 bytes. The last variable "s" is also padded with and addition 2 bytes.

Even though 8 total bytes are declared, the RAM usage is 12 bytes.

If you rearrange to:
Code:
[blue]Dim[/blue] i [blue]As[/blue] Int32 [green]'4 bytes[/green]
[blue]Dim[/blue] s [blue]As[/blue] Int16 [green]'2 bytes[/green]
[blue]Dim[/blue] b [blue]As[/blue] Byte  [green]'1 byte[/green]
"i" fits into one 4 byte segment. Since "s" and "b" are declared one after the other, you can fit them both into a segment...3 bytes total then 1 byte padding to complete the segment.

You now are using 8 bytes instead of 12.

Is this necessary in .NET?
 
hmmm...I have no idea. My first thought is that it shouldn't considering that .net is managed by the CLR; but I may be wrong
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top