Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte vs Short vs Int (Along With The Unsigned Variation) In C#?

Tags:

c#

types

memory

cpu

I was told, that as long as memory size was not a huge concern, it is always better to use an int instead of a byte or short because it is actually easier for the CPU to handle an int (the CPU needs to do extra stuff to work with bytes and shorts). Is this true in C#?

like image 391
ryanzec Avatar asked Feb 21 '11 10:02

ryanzec


1 Answers

It depends more on the processor than on the language. An 8-bit microcontroller will almost certainly be able to access an 8-bit char faster than a 32-bit int.

Being aware of this limitation allows algorithm designers to plan accordingly: One of the reasons why Rijndael won the AES competition is because the designers had planned for making 8-bit versions as fast as possible, in addition to caring about execution speed on 32-bit or larger processors.

But for 32-bit and 64-bit microprocessors, data alignment and bulk data access is key: int accesses are frequently much faster than char accesses, and long long (64 bit) may be faster still for some systems. (But the 64-bit operations on a 32-bit machine are much slower, so using 64-bit datatypes makes most sense when the data actually makes more sense in 64 bits.)

like image 178
sarnold Avatar answered Oct 15 '22 04:10

sarnold