Reading All possible C# array initialization syntaxes I wondered why C# always infers an array of int/Int32
where a smaller data type such as byte
or short
would suffice.
new[] { 30, 130, 230 } // sbyte[] suffices but becomes int[]
new[] { -1, 125, -119 } // sbyte[] suffices but becomes int[]
new[] { -31647, -1337, 23456} // short suffices but becomes int[]
In the referenced question, Eric Lippert states that the 'best type' is used - see below, but how is int
the best possible type? If we are going for overkill, why not use long
then?
The type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type.
I would suspect that processing 8 or 16-bit datatypes could be faster than 32-bit structures, e.g. when using SIMD where four byte
instances could fit in the register space of one int/Int32
. I know that SSE instructions are not (widely) used by the JIT Compiler, but this usage of 'int
everywhere' ensures that it will not help much when the JIT Compiler is going to include such optimizations.
Could someone elaborate on these facts and tell why it always resorts to int
?
// Edit //
I don't really care about the specification that prescribes that a literal without a prefix should be considered an int
. To rephrase the question:
Why are datatypes used that are larger than needed? Why does the specification have this rule for literals? What are the advantages since the huge downside is the away from future (SIMD) optimizations.