Idea for avoiding GC for lambdas
Steven Schveighoffer
schveiguy at gmail.com
Tue Jun 22 19:56:03 UTC 2021
On 6/22/21 12:13 PM, H. S. Teoh wrote:
> Unless I'm missing something obvious, I don't think value delegates
> would work well with D, because it's pretty important for delegates with
> the same parameter and return types to be interchangeable. I.e., two
> delegates with external type `int delegate(string)` must have the same
> fixed size and memory layout, regardless of the size of the context of
> one delegate vs. the other, otherwise you have a pretty serious problem
> at the language level.
This again, is a misunderstanding of my proposal. I'm not talking about
altering delegates in any way.
There are no delegates involved in `filter`. It is, instead, an inner
struct with a hidden context pointer. Could just as well be a struct
with context carried with it instead of allocated on the heap.
Note that this generates 2 *different* `FilterResult` instances, because
they are 2 different lambdas:
```d
int[] arr = [1, 2, 3];
auto f1 = arr.filter!(v => v % 2);
atuo f2 = arr.filter!(v => v % 2);
static assert(!is(typeof(f1) == typeof(f2)));
```
I'm unclear how the compiler generates and passes the context, but I
know that it uses the GC. However, it would be reasonable to allow
functions to accept the context by value (if it makes sense). One way to
do this is to work out whether you can do it by value, and use that if
possible. Another way is to explicitly have different syntax to pass the
context by value.
I was hoping for a possible way forward where the compiler figures it
all out for me.
-Steve
More information about the Digitalmars-d
mailing list