Open
Description
Was tinkering around JIT generated code for List<>
and raw arrays for very simple below code.
public static void ListUsage()
{
List<int> numbers = new(1);
numbers.Add(1);
Console.WriteLine(numbers[0]);
}
public static void ArrayUsage()
{
int[] numbers = new int[1] {1};
Console.WriteLine(numbers[0]);
}
public static void Expected()
{
Console.WriteLine(1);
}
The code is very self explanatory, nothing magical or complex as such. I was comparing the machine code generated by each method. I was expecting JIT to see the code flow and optimize the code gen generated for ListUsage
and ArrayUsage
to be similar as Expected
method, but it does not.
Below are things JIT can see and I would expect it to optimize it further.
- JIT can see
List<int> numbers
(in methodListUsage
) andint[] numbers
(in methodArrayUsage
) are declared inside the method and get destroyed in method itself at the end (does not get pass to any other method). It even sees the maximum size of those data structure which is1
so ideally it should stack allocate those instead of doing heap allocation. - The number that is getting added to collection is pure constant (1), so its not dynamic value. And on very next line we are even printing it directly by indexing and after that the method ends. So ideally JIT should see this flow and should optimize the code gen just like the code-gen generated by
Expected
method in above code.
Tested against main branch on CC => https://godbolt.org/z/eWv6Yaoaj