Say I’m looping through like 20/30 objects or in any other case where I’m dealing with smaller numbers, is it a good practice to use short instead of int?
I mean why isn’t this common:
for(short i=0; i<x; i++)
Method(array[i]);
Is it because the performance gain is too low?
Thanks
“is it a good practice to use short instead of int?”
First of all, this is a micro optimization that will not achieve the expected results: increase speed or efficiency.
Second: No, not really, the CLR internally still uses 32 bit integers (Int32) to perform the iteration. Basically it converts short to Int32 for computation purposes during JIT compilation.
Third: Array indexes are Int32, and the iterating short variable is automatically converted to int32 when used as an array indexer.
If we take the next code:
And disassemble it, you can clearly see at
00000089 inc eaxthat at machine level an 32 bit register was used for the iterating variable (eax), which is next truncated to 16 bit0000008a movsx eax,axso there are no benefits from using a short oppossed to using an int32, actually there might be a slight performance loss due to extra instructions that need to be executed.