In my post on functional effect systems, I mentioned in passing that FIO “has to emulate type erasure at runtime to interpret effects of arbitrary types”, and left it at that. This post is about how FIO hid the types in its effects from my thesis onwards, what that cost, and the class hierarchy that replaced it in 0.6.0-beta.
FIO used to forget an effect's types by copying the effect, so every FlatMap paid for a copy. Now every kind of effect is its own class, and forgetting the types costs nothing. Here's how run time changed against the commit just before the rewrite, on an M4 Max under macOS (negative is faster):
| Change in run time | WorkStealing | Direct |
|---|---|---|
| All 28 macro benchmark cases | −7.0% | −10.3% |
| Counting | −27% | −29% |
| Pingpong 50000 | −19% | −10% |
| Threadring 100×1000 | −16% | −33% |
| Fork 1000 | +1.2% | −1.5% |
Every workload allocates less, between 16% and 68% less, and running a FlatMap allocates 144 bytes instead of 520, a Map 104 instead of 288. The rest of this post is the story behind those numbers.
One Interpreter, Many Types
An effect of type FIO<'A, 'E> succeeds with an 'A or fails with an 'E. Composing effects changes those types as you go. FlatMap takes an FIO<'A, 'E> and a function 'A -> FIO<'B, 'E> and returns an FIO<'B, 'E>, so a program is a tree where every node can have different type arguments.
The runtime runs that tree in a single loop. It looks at the current node, works out what kind it is, takes a step, and moves on. A loop rather than recursion means a deep tree never grows the call stack, and it gives the runtime somewhere to stop between steps, to let another fiber run or to notice an interruption. A generic function is instantiated at one set of type arguments, but this loop meets a new set at every node, and it only finds out which at runtime. Somewhere, the types have to be forgotten.
On the JVM that comes for free. Scala's generics are erased when the code is compiled, so ZIO's run loop takes every effect as a ZIO[Any, Any, Any] (in ZIO's source the type is literally called Erased) and nothing at runtime checks the difference. I had only a little experience with ZIO before my thesis, and one of the first surprises of bringing its ideas to F# was that .NET doesn't work like that. .NET generics are reified, so an FIO<int, exn> and an FIO<obj, exn> are different types at runtime, and you can't cast one to the other.
The natural way to write an effect type in F# is a discriminated union. Here's a toy one with two cases, where Bind is what FlatMap builds:
type Eff<'A> =
| Pure of 'A
| Bind of Eff<'X> * ('X -> Eff<'A>)
The compiler rejects it with The type parameter 'X is not defined. A Bind needs to hold an effect of some type 'X together with a function from that same 'X, and a union case can't introduce a type parameter of its own. That's an existential type (“there is some 'X, and these two agree on it”). Haskell has them through GHC extensions, and Scala gets the same thing from subclassing, which I'll come back to. F# has neither existential types nor GADTs.
I think GADTs would be a great addition to the language. They include existential types, so a case like Bind could have its own 'X, and FIO could have kept a union at its core instead of a class hierarchy.
Erasing to obj
The answer I settled on in my thesis, and the one FIO lived with until this rewrite, was to give up on the hidden type and use obj, the one type every value converts to:
type Eff<'A> =
| Pure of 'A
| Bind of Eff<obj> * (obj -> Eff<'A>)
That compiles, and the interpreter can treat every inner effect as an Eff<obj>. The trouble is in flatMap, the toy's version of FIO's FlatMap, which has to build that Bind. It's handed an Eff<'A> and needs an Eff<obj>, and since generics are reified, a union at one type argument isn't a subtype of the same union at another:
box (Pure 42 : Eff<int>) :?> Eff<obj> // InvalidCastException
The only way to get an Eff<obj> is to build one. So flatMap rebuilds it, boxing values and wrapping continuations as it goes:
let rec erase<'A> (eff: Eff<'A>) : Eff<obj> =
match eff with
| Pure value -> Pure(box value)
| Bind(inner, cont) -> Bind(inner, fun x -> erase (cont x))
let flatMap (f: 'A -> Eff<'B>) (eff: Eff<'A>) : Eff<'B> =
Bind(erase eff, fun x -> f (unbox<'A> x))
Look at the Bind case of erase. It can't erase the effect the continuation will return, because that effect doesn't exist yet, so it wraps the continuation in a new closure that erases the result when it arrives. That laziness is what keeps it correct, and it's also what makes it expensive, because every time the continuation runs it builds a fresh erased copy of whatever it returned.
The real FIO had the same shape at a larger scale. Here's its code, trimmed:
and FIO<'A, 'E> =
internal
| Success of value: 'A
| Failure of error: 'E
// …
| ChainSuccess of effect: FIO<obj, 'E> * cont: (obj -> FIO<'A, 'E>)
// …
member this.FlatMap<'A1> (cont: 'A -> FIO<'A1, 'E>) : FIO<'A1, 'E> =
ChainSuccess(this.UpcastResult(), fun value -> cont (value :?> 'A))
member internal this.UpcastResult () : FIO<obj, 'E> =
match this with
| Success value ->
Success(value :> obj)
// …
| ChainSuccess(effect, cont) ->
ChainSuccess(effect, fun value -> cont(value).UpcastResult())
// … one case for every kind of effect
There were three of these, UpcastResult, UpcastError and UpcastBoth, and each had a case for every kind of effect. Operations change different parameters, which is why there were three. FlatMap changes the result type, CatchAll the error type, and Fork and Ensuring hand an effect to code that knows neither, so each erased only what it had to and kept the rest typed.
Not all of the rebuilding could be lazy, either. A ChainSuccess already holds its inner effect as an FIO<obj, 'E>, so erasing its result type only means wrapping the continuation. Erasing its error type means rebuilding the inner effect too, and that effect's inner effect, all the way down a chain of FlatMaps. Done recursively, a long chain would overflow the stack, so a set of flatten helpers walked those chains in a loop instead.
I did try something else during the thesis, a visitor-style encoding where a node hands its hidden type to a generic method instead of giving it up. I went with the casts because they were easier to implement and fit the functional style I wanted for the rest of FIO. I still think that was a reasonable call. The design was type-safe from the outside, and every cast inside it was guaranteed to succeed.
What Erasure Cost
It always bugged me, though. There were casts everywhere, which looked wasteful, but I couldn't see another way to emulate erasure on .NET. I was sure there was one.
When I finally measured it, the casts weren't where the cost was. Running one FlatMap allocated 520 bytes, and a Map 288. Those numbers come from the commit just before the rewrite. An earlier change in the same release had already given Map a case of its own, but that's a story for another post. After the rewrite, the same FlatMap allocates 144 bytes, so 376 of the 520 went to forgetting types, in erased copies and closures wrapped around closures.
That matters more in an effect system than in most code, because everything is built from these two operations. A ping-pong between two fibers, a fork/join tree or a server's request loop is mostly binds and maps, run millions of times.
A Class per Effect
The way out came up while I was working on FIO's performance with Claude Code. It suggested giving every kind of effect its own class. It looked like the answer I'd been missing, though I didn't trust it until the measurements backed it up. I had been asking a union to do something a class hierarchy does naturally. In .NET, treating a subclass as its base class costs nothing, with no copy and no runtime check. If every effect node is a class derived from one base that isn't generic, so that a single type can hold any node, then forgetting a node's types just means looking at it through that base.
Here's the toy again, rebuilt that way:
open System.Collections.Generic
type Kind =
| Pure
| Bind
[<AbstractClass; AllowNullLiteral>]
type Node(kind: Kind) =
member _.Kind = kind
abstract Value: obj
abstract Child: Node
abstract Continue: obj -> Node
[<AbstractClass>]
type Eff<'A>(kind: Kind) =
inherit Node(kind)
type PureNode<'A>(value: 'A) =
inherit Eff<'A>(Pure)
override _.Value = box value
override _.Child = null
override _.Continue _ = invalidOp "a pure node has no continuation"
type BindNode<'A, 'B>(inner: Eff<'A>, cont: 'A -> Eff<'B>) =
inherit Eff<'B>(Bind)
override _.Value = invalidOp "a bind node has no value"
override _.Child = inner
override _.Continue value = cont (value :?> 'A)
let flatMap (f: 'A -> Eff<'B>) (eff: Eff<'A>) : Eff<'B> = BindNode(eff, f)
BindNode<'A, 'B> is the existential type the union couldn't express. Its 'A is a real type parameter, but from the outside it's just an Eff<'B>, and to the interpreter just a Node. flatMap stores its input as it is. The one cast left, value :?> 'A, runs when the value is handed to your function, inside the class that knows what 'A is.
The interpreter only ever sees Node:
let run (eff: Eff<'A>) : 'A =
let frames = Stack<Node>()
let mutable current: Node = eff
let mutable result = null
let mutable running = true
while running do
match current.Kind with
| Bind ->
frames.Push current
current <- current.Child
| Pure when frames.Count = 0 ->
result <- current.Value
running <- false
| Pure -> current <- frames.Pop().Continue current.Value
unbox<'A> result
That's a lot more code than the union. Every kind of effect needs a class of its own, and in the real FIO many of them get an ops class as well (more on that below), where the union needed one line per case. But most of that code is declarations. Building a Bind now just stores what it was given, and no function walks the effect to rebuild it. The union was shorter to write, and it did more work every time a program ran.
Here's a single FlatMap in the real FIO, before and after the rewrite, with a = FIO.succeed 1. The highlighted objects are the ones FlatMap allocates:
a.FlatMap f allocates. Before: a ChainSuccess, an erased copy of a with its value boxed, and a closure that wraps f. After: one BindNode, pointing at a and f as they are.This is also how the Scala libraries are built. In Cats Effect, FlatMap is a case class with a type parameter of its own, FlatMap[E, +A](ioe: IO[E], f: E => IO[A], …) extends IO[A], and ZIO's FlatMap is built the same way. A Scala ADT is a class hierarchy to begin with, so the existential comes with it.
FIO's real version has the same idea with two refinements. The base type, FIOBase, stores a node's payload in two plain fields, A and B, which the interpreter reads directly, so stepping into a node needs no virtual call. Only handing a value to your code does. That matters in a loop that takes millions of steps. Two fields turn out to be enough for everything the interpreter reads itself, often a child or a function in one and the ops object in the other. Whatever only typed code needs, like a BindNode's continuation, stays in a field of the node's own class.
The typed code (calling your continuation, your mapper, your error handler) lives on a separate NodeOps object, one per combination of type arguments. Virtual methods on the node classes would have been the obvious home, but an abstract member is always exactly as visible as its type (F# rejects anything else with FS0561), and the interpreter would have to call them through the public FIOBase, so they would have become public API. On the internal NodeOps they stay hidden. That code is the same for every node of a given type, so the nodes share one instance, and each pays only for the reference to it in B. Here's the code, trimmed:
and [<AbstractClass; NoEquality; NoComparison>] FIOBase =
val internal Kind: NodeKind
val internal A: obj
val internal B: obj
// …
and [<AbstractClass; NoEquality; NoComparison>] FIO<'A, 'E> =
inherit FIOBase
// …
member this.FlatMap<'A1> (cont: 'A -> FIO<'A1, 'E>) : FIO<'A1, 'E> =
BindNode<'A, 'A1, 'E>(this, cont)
and [<Sealed>] internal BindNode<'A, 'B, 'E>(inner: FIO<'A, 'E>, cont: 'A -> FIO<'B, 'E>) =
inherit FIO<'B, 'E>(NodeKind.Bind, inner, BindOps<'A, 'B, 'E>.Instance)
// …
member _.Cont = cont
and [<Sealed>] internal BindOps<'A, 'B, 'E> private () =
inherit NodeOps()
// …
override _.Continue (node, value) =
let effect = (cast<BindNode<'A, 'B, 'E>> node).Cont (value :?> 'A)
// …
effect
The cast there isn't a checked cast. In a Release build it's Unsafe.As, which reinterprets the reference without looking at it. Only a BindNode<'A, 'B, 'E> ever carries a BindOps<'A, 'B, 'E>, so the ops object already knows what class the node is, and checking again would cost something on every step. The flip side is that a mismatch in Release wouldn't throw. It would quietly read the wrong fields. So Debug builds check the cast, and CI runs every test suite on a -p:FioCheckedCasts=true build that checks it too. Unsafe code in a library other people depend on makes me nervous, and I only accept it here because this is the hottest path FIO has. The only real type check left on this path is value :?> 'A, the same one the old design made.
On a Bind, the interpreter steps into the inner effect and pushes a frame that remembers the node:
| NodeKind.Bind ->
state.Effect <- node.Child
state.ContStack.Push(ChainCont(node, Unchecked.defaultof<_>))
ValueNone
The frame holds the node itself rather than a continuation, since the node already carries the typed continuation and the ops that call it. The frame is a struct, so pushing one doesn't allocate. When the inner effect succeeds, the interpreter pops the frame and calls node.Ops.Continue(node, value), and that's the only place the types come back.
One more language rule shaped the details: the interpreter can't dispatch on type tests. :? BindNode<_, _, _> doesn't mean "any BindNode". F# infers the wildcards, and with nothing to infer them from it fixes them to obj and warns about it (FS0064), so the test matches BindNode<obj, obj, obj> and nothing else. So every node carries a NodeKind, a fieldless union the interpreter matches on. It's a union rather than an enum because F# never treats a match on an enum as complete (FS0104 warns that an enum can hold values outside its cases), so the match would need a wildcard and the compiler couldn't check it. As a union, the match is exhaustive, and since FIO builds with warnings as errors, a new kind of effect the interpreter forgets to handle fails the build. Cats Effect does much the same with an integer tag on every node.
Measuring It
A change like this is easy to get wrong in both directions. Benchmark timings on a dev machine drift by tens of percent between sessions, so one before-and-after run proves nothing. I wrote most of the rewrite in the evenings over a week at the end of October, and left a lot of performance runs going overnight. They followed the protocol in FIO's benchmark README. The old and new builds ran back to back, workload by workload, with a fixed sentinel benchmark before, during and after to show how much the machine itself drifted. Allocations could be compared directly, since unlike timings they barely move between runs. I worked out the design from that first suggestion and set the rules for what would count as a win, and Claude Code did the legwork of building both trees, running the pairs and collecting the numbers.
Before anything ran, every operation got a written prediction of how many bytes it should allocate under the new design. Writing them down first meant I couldn't bend the explanation afterwards to fit the results. They came out exact, which was the best evidence I had that the design did what I thought it did.
What the Rewrite Cost
It wasn't free everywhere. Fork 1000 on the work-stealing runtime got 1.2% slower, inside the 2.1% allowance, which was how far the sentinel benchmark drifted during that session. A handful of micro-benchmarks read slower too, a write to a full bounded channel among them. And building some effects got more expensive. FIO.succeed 1 now allocates 64 bytes instead of 24. A success node boxes its value as soon as it's built, so the interpreter can read it straight from A like any other payload, and every node carries the same kind field and two slots. The old union case kept the int unboxed, but every erasure boxed it again, and now it's boxed once. Constructing a ZipPar, Race or RaceFirst went from 120 bytes to 208 for the same reason. Most effects are built while a program runs, by the continuations themselves, so these costs land on the hot path too. They're outweighed, though: every workload allocates less overall, and running allocates less on every operation measured.
There's a memory cost as well. A frame on the continuation stack now holds its node, and with it the node's whole subtree, until the frame is popped, where the old FlatMap frame held only the continuation. It's bounded, since it never builds up across a tail-recursive loop, and a fio { } block cuts it off, because the block starts with a node that holds only a thunk.
I only measured on macOS. The tests pass on Linux and Windows too, but how the numbers hold up there is still an open question.
Looking Back
I'm still fond of the old design. It took FIO from a thesis to a NuGet package. But for four years I assumed the casts were the waste, and the rewrite kept the same cast and still got faster. The cost was in copying an effect to get one whose type said obj, and the fix was to look at a node through its base class instead of copying it into a new one.
There's some irony in where the fix came from. Functional programming is what got me away from Java and its class hierarchies, and a class hierarchy is what fixed FIO. It sits underneath the functional API, though, and nothing you write with fio { } ever sees a node class.
FIO is on GitHub, and the 0.6.0-beta pull request has the full benchmark results.