Which integer is the fastest?
Choosing the right type of integer to use can have an impact on the performance of your system. I wouldn’t worry too much about this: the CLR is pretty good at optimizing your code, and the just-in-time (JIT) compiler also applies many optimizations. Let’s consider an example. Imagine that we have a for
loop that iterates over a piece of code. If we have less than 255 iterations, we might be tempted to use a byte. After all, a byte is just 1 byte. If you use an integer, it will be 4 bytes. That is more memory and probably takes longer to process, right?
Wrong!
Don’t try to outsmart the compiler. It knows the system a lot better than you do.
Let me show you.
We have the following four lines of C# code:
var a = byte.MaxValue; var b = UInt16.MaxValue; var c = UInt32.MaxValue; var d = UInt64.MaxValue;
We set four variables to some values. The following table describes the specifics of each type: