Possible Duplicate:
The importance of using a 16bit integer
If today’s processors perform (under standard conditions) 32-bit operations — then is using a “short int” reasonable? Because in order to perform an operation on that data, it will convert it to a 32-bit (from 16-bit) integer, perform the operations, and then go back to 16-bit — I think. So what is the point?
In essence my questions are as follows:
- What (if any) performance gain/hindrance does using a smaller ranged integer bring? Like, if instead of using a standard 32-bit integer for storage, I use a 16-bit short integer.
- “and then go back to 16-bit” — Am I correct here? See above.
- Are all integer data stored as 32-bit integer space on CPU/RAM?
The processor doesn’t need to “expand” a value to work with it. It just pads the unused spaces with zeroes and ignores them when performing calculations. So, actually, it is faster to operate on a
short intthan along int, although with today’s fast CPUs it is very hard to notice even a bit of difference (pun intended).The machine doesn’t really convert. When changing the size of a value, it either pads zeroes to the left or totally ignores extra bits to the left that won’t fit in the target memory region.
No, and this is usually the reason people use
short intvalues for purposes where the range of along intjust isn’t needed. The memory allocated is different for each length ofint, like ashort inttakes up fewer bits of memory than along int. One of the steps in optimization is to changelong intvalues toshort intvalues when the range does not exceed that of ashort int, meaning that the value would never use the extra bits allocated with along int. The memory saved from such an optimization can actually be quite significant when dealing with a lot of elements in arrays or a lot of objects of the samestructorclass.Different
intsizes are stored with different amounts of bits in both the RAM and the internal processor cache. This is also true offloat,double, andlong double, althoughlong doubleis mainly for 64-bit systems and most compilers just ignore thelongif running on 32-bit machines because a 64-bit value in a 32-bit accumulator & ALU will be ‘mowed down’ during any calculation and would likely never receive anything but zeros for the first 32 bits.