字节变量如何存储在内存中? [英] How are byte variables stored in memory?

查看:239
本文介绍了字节变量如何存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本有关C#的书( Pro C#和.NET 4平台(由安德鲁·特罗尔森撰写)),我已经阅读了以下段落:

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

更改基本类型 枚举可能对您有所帮助 建立一个.NET应用程序,它将 部署到低内存设备 (例如启用.NET的手机或 PDA),并且需要节省内存 尽可能地.

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.

字节使用更少的内存是真的吗?出于性能原因,它们不是存储在4个字节上吗?我记得在某处读过后者,但即使在C#规范中也找不到任何有关它的信息.

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.

推荐答案

这并不简单.作为方法中的变量,它们与int几乎相同,因此为4字节.在数组中,它们是单字节的.作为一个领域...我需要检查一下; 猜测填充意味着它们可以被视为4字节.带有sizeofstruct应该显示...

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
    }
}

此处i显示3,因此它们是单字节字段,但是(请参阅codymanix的注释)当涉及其他类型时,可能需要附加填充-例如:

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;
}

8 个字节,因为需要对齐d.好玩好玩.

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

这篇关于字节变量如何存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆