Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid closures due to implementations in local functions #906

Closed
viceroypenguin opened this issue Nov 26, 2022 · 1 comment · Fixed by #1064
Closed

Avoid closures due to implementations in local functions #906

viceroypenguin opened this issue Nov 26, 2022 · 1 comment · Fixed by #1064
Labels
Milestone

Comments

@viceroypenguin
Copy link
Contributor

Currently, most operators are implemented as such:

public static IEnumerator<TSource> Operator<TSource>(this IEnumerable<TSource> source, ...)
{
   // guard statements
   return _();

   _()
   {
      yield return source.First();
      yield break;
   }
}

A better implementation would be the following:

public static IEnumerator<TSource> Operator<TSource>(this IEnumerable<TSource> source, ...)
{
   // guard statements
   return _(source, ...);

   static _(IEnumerable<TSource> source, ...)
   {
      yield return source.First();
      yield break;
   }
}

With the current implementation, the host method must create a closure class before even doing guard statements, copy parameters, and then call a method on that closure class. This means that there are two closure classes: one for the parameters, and one for the enumerator.

Switching to passing the parameters into the iterator method means that only one closure class has to be created, the one for the enumerator; the parameters will be held by that class. This should simplify and improve the IL, the JIT, and the output JIT-ted code.

@atifaziz
Copy link
Member

Thanks for bringing this up and shame about the closure because it means reverting all of #290. The local functions really made things pleasant (for all the reasons listed in #290), but I agree that inducing a closure is not worth the cost. In fact, if the local function is going to be static, then it might as well be a private method again.

@atifaziz atifaziz changed the title Simplify Closures Avoid closures due to implementations in local functions Jun 27, 2023
@atifaziz atifaziz added this to the 4.3.0 milestone Apr 27, 2024
atifaziz added a commit that referenced this issue May 1, 2024
This is a squashed merge of PR #1064 that:

- closes #906
- fixes #1065

---------

Co-authored-by: Atif Aziz <code@raboof.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants