Skip to content

JIT - Folding unwanted foreach with empty list. #61455

@ShreyasJejurkar

Description

@ShreyasJejurkar

I was playing with the .NET 6 JIT compiler with sharplab. Found the following interesting scenario, where we can do optimizations.

using System;
using System.Collections.Generic;

List<string> names = new();

foreach(var item in names)
    Console.WriteLine(item);

In the above scenario, can JIT detect that names list is an empty list and in program execution flow, no element is added to that list.? Although if anyone enumerated that list, nothing will happen and so can't JIT detect this behavior and fold foreach loop to nothing?

Right now, JIT emits assembly code for foreach loop, as we can see below in the link, which I think no use and can be avoided.

https://sharplab.io/#v2:EYLgtghglgdgNAFxBAzmAPgAQEwAYCwAUDgIxGa4AEmJALANxFEAyUKCAPDbgHyUwQwAUxSUAvPyEB3ABQBKRoSIAzAPYAnIRADGACxkA3COspQEQsKZj9BIuUUqPqJAJwyzFhUSA===

@EgorBo @AndyAyersMS

category:cq
theme:basic-cq
skill-level:expert
cost:large
impact:medium

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