C# number sizes 8, 16, 32 etc bits

blackwidow_rsa

Distinguished
Aug 16, 2007
26
0
18,580
well my question is whether 8bit or 16bit takes less space than 32 bit ints?
technically they should but with 32bit processor does the size increase automatically to
32bits or do they stay the same (8 or 16)?

sorry if this sounds stupid, but i just started on C# at college and did some
java in high school.

having everything @ 32bits would certainly make things easier.
but i'd rather have more memory effecient programs.

thanks alot. :hello:
 

Ijack

Distinguished
I think that the CLR aligns data on 4 byte boundaries, with padding inbetween. This would mean that there is no space advantage to using the smaller data types. (But I'm not sure how arrays are stored.) It's quite possible that the processor might be able to handle some data types more efficiently than others but, even if that were the case, I can't see that affecting the speed of your programs much.

From a purist point of view I would say that you should always use the most appropriate size of integer (e.g. if your variable stores days of the week use and 8-bit int; in Pascal you would define a data type that can only take the values 0-7) and don't worry too much about the underlying implementation. What is true at a low level today won't necessarily always be so. Also this is good practice when using a selection of programming languages.
 

Scott2009

Distinguished
Sep 20, 2009
15
0
18,560
It may align the data on 4 byte or 8 byte boundaries, however it will still process faster by the ALU/CPU.

Search MSDN / TechNet for "SSE" or "MMX", etc
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
I would side with ijack on the "use the appropriate type" as much as possible. First, you don't know if the compiler will do magic in optimizing the code, maybe there is some magic CPU operation that can process two 16 bits operations in a single pass on a 32 bits CPU. Secondly, if the operation is actually done in 32/64 bits registers, the data might not be stored in cache with it's real size and cache is still very limited compared to RAM. Someone more familiar with assembly-level programming could probably give good pointers.