Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bytes will a string take up?

Tags:

string

c#

byte

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

string abc = "a"; 
like image 575
Mohit Kumar Avatar asked Oct 19 '10 10:10

Mohit Kumar


People also ask

How many bytes does a string take in C?

A char , by definition, takes up one byte.

How much data does a string take?

It depends on the encoding, ebcdic take 4 bits for character. UTF-8 take 8 bits per character (one byte). Some encodings use both 8 bits and 16 bits for representing characters...

How many KB is a string?

length" represents the number of bytes in the string const KB: number = (string. length / 1024).

How much can a string hold?

MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.) So you can have a String of 2,147,483,647 characters, theoretically.


1 Answers

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...)

like image 200
Jon Skeet Avatar answered Oct 11 '22 14:10

Jon Skeet