Link to home
Start Free TrialLog in
Avatar of ianinspain
ianinspain

asked on

Deciding which type to use?

Hi there,

I was wondering which is the best type to use, let me explain... When ever i am using an integer for example then I would generally use int (int32) for example

But what if i need to only store either 0 or 1, then is it better to use a Byte type rather than another type or an int?

This does seem pretty logical to me but before making mistakes i thought i would ask.

Basically the rule should be use the smallest int possible or use a byte etc..., takes up less space in memory but what about optimisation, using a byte wouldn't take more time to run than using say an int (int32)??

Just wanted some clarification

Regards

I
Avatar of AlexFM
AlexFM

For variable which can be 0 or 1 consider using bool (System.Boolean) type.
However, if you want to use this variable in arithmetic (not logical) expressions, use int or byte.
Using smallest possible type saves memory, but sometimes may reduce performance. For example, processor doesn't like unaligned addresses and array of integers may be handled faster than array of bytes. This depends on situations where this variable will be used.
Avatar of ianinspain

ASKER

Thanks AlexFM,

This is what I thought, so I suppose its a trade off of weather I want to save memory or performance.

Are there any set rules?

Or should i just always use the smallest type possible for the calculation? or just use ints ??

The reduce in performance is worth the save in memory or visa versa?

I
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Much appreciated!

That cleared up some concerns! Thanks
Processor doesn't like unaligned addresses. Single variable or class member will be aligned to 32-bits boundary. In this case, byte takes the same space and performs exactly like int. But array of bytes is better than array of integers, because array members are not aligned.