Skip to content

JIT fails to escape simple usage of List<> and [] #111838

Open
@ShreyasJejurkar

Description

@ShreyasJejurkar

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.

  1. JIT can see List<int> numbers (in method ListUsage) and int[] numbers (in method ArrayUsage) 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 is 1 so ideally it should stack allocate those instead of doing heap allocation.
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions