neo2862
neo2862

Reputation: 1526

How are byte variables stored in memory?

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.

Upvotes: 7

Views: 1808

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1064114

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.

Upvotes: 8

codymanix
codymanix

Reputation: 29540

I don't think that this is explicitly defined by the C# or even .NET specification. You should use the StructLayout and FieldOffset attributes to specify exact memory layout.

[StructLayout(LayoutKind.Sequential, Pack=1)]
struct TestDByte
{
    public double a;
    public byte b;
}

Upvotes: 2

MartinStettner
MartinStettner

Reputation: 29174

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.

Upvotes: 2

Csaboka
Csaboka

Reputation: 11

Bytes don't need to be aligned to work efficiently on x86 CPUs (larger units do, though). For other CPU architectures, things may work differently.

Upvotes: 1

Related Questions