Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are byte variables stored in memory?

Tags:

c#

memory

byte

I'm reading a book about C# (Pro C# and the .NET 4 Platform by Andrew Troelsen) and I've just read this paragraph:

Changing the underlying type of an enumeration can be helpful if you are building a .NET application that will be deployed to a low-memory device (such as a .NET-enabled cell phone or PDA) and need to conserve memory wherever possible.

Is it true that bytes use less memory? Aren't they stored on 4 bytes for performance reasons? I remember reading the latter somewhere but I can't find any info about it, not even in the C# specification.

like image 996
neo2862 Avatar asked Dec 05 '10 11:12

neo2862


2 Answers

It isn't simple. As variables in a method, they are pretty much the same as int, so 4-byte; inside an array they are single-byte. As a field... I'd need to check; I guess padding means they may be treated as 4-byte. A struct with sizeof should reveal...

struct Foo {
    byte a, b, c;
}
static class Program {
    unsafe static void Main() {
        int i = sizeof(Foo); // <==== i=3
    }
}

Here i shows 3, so they are single-byte as fields, but (see comments by codymanix) additional padding may be needed when other types get involved - for example:

struct Foo
{
    byte a, b, c;
    int d;
}

is 8 bytes, due to the need of d to be aligned. Fun fun fun.

like image 182
Marc Gravell Avatar answered Oct 11 '22 19:10

Marc Gravell


I think it depends on the target platform. On "low-memory"-devices, the CLR may choose to pack them tightly, so it will save memory if you change the enumeration type.

like image 32
MartinStettner Avatar answered Oct 11 '22 18:10

MartinStettner