dotnet / dotnet/vblang

Minimalist code generation for simple lambdas.

Open
#131 6 comments 2 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
328
Forks
71
PR merge metrics
No merged PRs in 30d

Description

Passing in functions/subs using lambdas is a very handy abstraction tool and will be used heavily in any sizable project. A simple example:

```vb
Public Sub Foo()
Dim data = New List(Of Integer) From {1, 2, 3}
data.ForEach(Sub(n) Console.WriteLine(n))
End Sub
```

The lambda sub passed to the `List.ForEach()` method makes NO REFERENCE to any members in the containing `Foo()` method however the compiler goes ahead and GENERATES A FULL CLASS to implement it as a closure, as follows:

```vb
Friend NotInheritable Class _Closure$__
Friend Sub _Lambda$__0-0(ByVal n As Integer)
Console.WriteLine(n)
End Sub

Public Shared ReadOnly $I As _Closure$__ = New _Closure$__
Public Shared $I0-0 As Action(Of Integer)
End Class
```

What's worse is it does this for every single little lambda sub/function you use (it has no de-duplication if the lambdas have identical bodies) and pretty soon these automatically generated closure classes add up, adding overhead to the assembly (in my current project I have over 45 such closure classes because I use lambdas heavily).

In the simple case (where a lambda depends purely on its arguments and does not touch the enclosing environment) the compiler should generate minimal code consisting of just one function. The previous example should ideally be implemented as follows:

```vb
Public Sub Foo()
Dim data = New List(Of Integer) From {1, 2, 3}
data.ForEach(AddressOf automatically_generated)
End Sub
Private Sub automatically_generated(n As Integer)
Console.WriteLine(n)
End Sub
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.