Tony said:
Hello!
I just wonder for example when having variables that contains numbers that
is less then the range for int
is it then any point to use types that is less then int for example byte or
short or ushort.
No, not really. In fact, if you expect your code to execute on the
64-bit platform primarily, you may even find that if anyting, Int64 or
UInt64 make more sense. Specific architectures have their "preferred"
data size, and accessing memory at smaller increments can actually hurt
performance, some times significantly.
But 32-bit integers are the current, most broadly used data size in new
mainstream code. They are a good default, barring any other criteria.
You should use the smaller data formats if you specifically need their
behavior (e.g. you have code that relies on truncation/overflow
behavior…normally, this wouldn't be a good idea, but sometimes it
happens), or you specifically need to match some external factor (e.g.
interop situations), or you are running in a constrained scenario where
the smaller size is the difference between the code working and not.
The vast majority of programming scenarios do not fall into those
categories.
Just for the example.
We could have a variable for the number of days in a week and
a variable for the number of days in a year and the number of second in a
minute and so on.
I doubt anybody will use a byte for storing the number of days in a week so
I assume most will use an int.
Yes, internally most implementations would just make everything ints,
assuming they really stored values separately like that.
Of course, in reality, date/time structures are normally represented
internally as a single integer or floating point value indicating a
specific number of time units since some specific reference point.
That's how the .NET DateTime struct works, for example.
But yes, if you're going to waste space storing individual fields for a
single unit of time like that, you might as well keep the code simple
and store ints. After all, in such a scenario you're obviously not that
concerned about getting the minimum stored size anyway.
Note that outside a program, the storage format is often non-binary
(e.g. XML) and so the width of the data type isn't relevant anyway. And
when it is, then you'd fall into the "some external factor" scenario I
mentioned above. The main consideration is typically limited to runtime
memory access and storage issues.
Pete