fslang-suggestions icon indicating copy to clipboard operation
fslang-suggestions copied to clipboard

Request for Delegate Generic Parameter Erasure for Span<T> Operations

Open RealmPlume opened this issue 3 months ago • 0 comments

*I propose we add support for type erasure of delegates with generic parameters, particularly for Span<T> operations, in order to allow performance optimizations similar to non-generic delegates.

The existing way of approaching this problem in F# is that custom delegates without generic parameters, such as AssignSpan, are subject to type erasure, which allows for optimizations. For example:

type AssignSpan = delegate of contain: Span<int> * index: int * value: int -> unit

let foo(xs: int[]) =
   let f = AssignSpan(fun span i x -> span[i] <- x)
   f.Invoke(xs.AsSpan(), 0, 1)

This code can be optimized to xs.AsSpan()[0] <- 1, which removes the overhead of the delegate invocation and improves performance.

However, when using generic parameters in the delegate, such as in AssignSpan<'T>, no such optimization is possible, as the generic type prevents erasure and optimizations:

type AssignSpan<'T> = delegate of contain: Span<'T> * index: int * value: 'T -> unit

let foo(xs: int[]) =
   let f = AssignSpan<int>(fun span i x -> span[i] <- x)
   f.Invoke(xs.AsSpan(), 0, 1)

In this case, no optimization occurs, and the code remains less efficient.

Pros and Cons

The advantages of making this adjustment to F# are:

  • Delegates involving Span<T> could be optimized similarly to non-generic delegates, which would result in performance gains.

  • The complexity of passing Span<T> operations via functions would be resolved, leading to simpler and more efficient code.

The disadvantages of making this adjustment to F# are:

  • No disadvantages have been identified so far.

Extra information

Estimated cost (XS, S, M, L, XL, XXL): M

Related suggestions: N/A

Affidavit (please submit!)

Please tick these items by placing a cross in the box:

  • [x] This is not a question (e.g. like one you might ask on StackOverflow

) and I have searched StackOverflow for discussions of this issue

  • [ ] This is a language change and not purely a tooling change (e.g. compiler bug, editor support, warning/error messages, new warning, non-breaking optimisation) belonging to the compiler and tooling repository

  • [x] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it

  • [x] I have searched both open and closed suggestions on this site and believe this is not a duplicate

Please tick all that apply:

  • [x] This is not a breaking change to the F# language design

  • [ ] I or my company would be willing to help implement and/or test this

RealmPlume avatar Sep 29 '25 07:09 RealmPlume