一个字符串多少字节占用? [英] How many bytes will a string take up?

查看:1641
本文介绍了一个字符串多少字节占用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我下面的字符串将有多少字节占用

 字符串ABC =一个?; 


解决方案

从我的article 的:




在目前的实现至少,串占用20+(N / 2)* 4个字节(四舍五入的n / 2下的值),其中n是字符串中的字符数。 string类型本身变化的物体的大小不同寻常。唯一的其他类里面做这个(据我所知)是数组。本质上,一个字符串是一个字符阵列中存储器,加上该阵列的长度和字符串的长度(字符数)。该阵列的长度并不总是一样的字符长度,作为字符串可以是过度分配mscorlib.dll中内,以使建立起来更容易。 (StringBuilder的做到这一点,例如。)当字符串是不可变到外面的世界,mscorlib程序中的代码可以改变的内容,所以StringBuilder的创建一个具有更大的内部字符数组比目前内容的字符串要求,则追加到该字符串,直到字符数组不再大到足以应付,此时它创建一个具有较大的阵列一个新的字符串。字符串长度成员也包含在其最高位标志要说字符串是否包含任何非ASCII字符。这使得在某些情况下,额外的优化。




我怀疑是写之前,我有机会与64位CLR工作;我怀疑在64位的土地每串占用4或8个字节以上。



编辑:我写了一个的blog帖子最近,其中包括64位信息(并稍微违背了上述86 ...)


Can anyone tell me how many bytes the below string will take up?

string abc = "a";

解决方案

From my article on strings:

In the current implementation at least, strings take up 20+(n/2)*4 bytes (rounding the value of n/2 down), where n is the number of characters in the string. The string type is unusual in that the size of the object itself varies. The only other classes which do this (as far as I know) are arrays. Essentially, a string is a character array in memory, plus the length of the array and the length of the string (in characters). The length of the array isn't always the same as the length in characters, as strings can be "over-allocated" within mscorlib.dll, to make building them up easier. (StringBuilder does this, for instance.) While strings are immutable to the outside world, code within mscorlib can change the contents, so StringBuilder creates a string with a larger internal character array than the current contents requires, then appends to that string until the character array is no longer big enough to cope, at which point it creates a new string with a larger array. The string length member also contains a flag in its top bit to say whether or not the string contains any non-ASCII characters. This allows for extra optimisation in some cases.

I suspect that was written before I had a chance to work with a 64-bit CLR; I suspect in 64-bit land each string takes up either 4 or 8 more bytes.

EDIT: I wrote up a blog post more recently which includes 64-bit information (and contradicts the above slightly for x86...)

这篇关于一个字符串多少字节占用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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