perf(effect): trim code pulled into minimal runtime bundles

- build the Hex decode table with a pure initializer so importing Tracer no
  longer keeps encoding/Hex in every bundle
- move FiberImpl.succeedWith, children and currentSpanLocal to module
  functions so they are only bundled with the combinators that use them
- fold the private PriorityBuckets class into MixedSchedulerDispatcher
This commit is contained in:
Tim Smart
2026-11-26 02:23:03 +00:00
parent 10bc4a47c0
commit daa93afc1e
4 changed files with 61 additions and 65 deletions
@@ -0,0 +1,5 @@
---
"effect": patch
---
Reduce the bundle size of minimal Effect programs such as `Effect.succeed(1).pipe(Effect.runFork)`.
+20 -32
View File
@@ -116,34 +116,6 @@ const setImmediate = (f: () => void) => {
}
}
class PriorityBuckets {
buckets: Array<[priority: number, tasks: Array<() => void>]> = []
scheduleTask(task: () => void, priority: number): void {
const buckets = this.buckets
const len = buckets.length
let bucket: [number, Array<() => void>] | undefined
let index = 0
for (; index < len; index++) {
if (buckets[index][0] > priority) break
bucket = buckets[index]
}
if (bucket && bucket[0] === priority) {
bucket[1].push(task)
} else if (index === len) {
buckets.push([priority, [task]])
} else {
buckets.splice(index, 0, [priority, [task]])
}
}
drain() {
const buckets = this.buckets
this.buckets = []
return buckets
}
}
/**
* Provides a scheduler implementation that batches queued tasks and dispatches them by
* priority.
@@ -215,7 +187,8 @@ export class MixedScheduler implements Scheduler {
}
class MixedSchedulerDispatcher implements SchedulerDispatcher {
private tasks = new PriorityBuckets()
// Ordered by ascending priority; tasks keep FIFO order within a bucket.
private buckets: Array<[priority: number, tasks: Array<() => void>]> = []
private running: (() => void) | undefined = undefined
readonly setImmediate: (f: () => void) => () => void
@@ -229,7 +202,21 @@ class MixedSchedulerDispatcher implements SchedulerDispatcher {
* @since 2.0.0
*/
scheduleTask(task: () => void, priority: number) {
this.tasks.scheduleTask(task, priority)
const buckets = this.buckets
const len = buckets.length
let bucket: [number, Array<() => void>] | undefined
let index = 0
for (; index < len; index++) {
if (buckets[index][0] > priority) break
bucket = buckets[index]
}
if (bucket && bucket[0] === priority) {
bucket[1].push(task)
} else if (index === len) {
buckets.push([priority, [task]])
} else {
buckets.splice(index, 0, [priority, [task]])
}
if (this.running === undefined) {
this.running = this.setImmediate(this.afterScheduled)
}
@@ -247,7 +234,8 @@ class MixedSchedulerDispatcher implements SchedulerDispatcher {
* @since 2.0.0
*/
runTasks() {
const buckets = this.tasks.drain()
const buckets = this.buckets
this.buckets = []
for (let i = 0; i < buckets.length; i++) {
const toRun = buckets[i][1]
for (let j = 0; j < toRun.length; j++) {
@@ -260,7 +248,7 @@ class MixedSchedulerDispatcher implements SchedulerDispatcher {
* @since 2.0.0
*/
flush() {
while (this.tasks.buckets.length > 0) {
while (this.buckets.length > 0) {
if (this.running !== undefined) {
this.running()
this.running = undefined
+5 -5
View File
@@ -284,10 +284,10 @@ const hexEncodeUint8Array = (bytes: Uint8Array): string => {
return result
}
const hexCodes = new Uint8Array(256).fill(255)
for (let i = 0; i < 16; i++) {
hexCodes["0123456789abcdef".charCodeAt(i)] = i
hexCodes["0123456789ABCDEF".charCodeAt(i)] = i
}
// Maps each byte to its hex digit value, or 255 when it is not a hex digit.
const hexCodes = Uint8Array.from({ length: 256 }, (_, charCode) => {
const digit = "0123456789abcdef".indexOf(String.fromCharCode(charCode).toLowerCase())
return digit === -1 ? 255 : digit
})
const hexCode = (charCode: number): number => charCode < 256 ? hexCodes[charCode] : 255
+31 -28
View File
@@ -757,17 +757,6 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
if (op[symbol]) return op as any
}
}
// Passes a success value straight to the next continuation instead of
// returning an Exit for the run loop to unwrap. Each call counts as an
// operation, and every `maxInlineSteps`th call returns an Exit instead, so
// continuations calling continuations never nest deeper than that.
succeedWith(value: unknown): Primitive | Yield {
if ((++this.currentOpCount & (maxInlineSteps - 1)) === 0) {
return exitSucceed(value) as any
}
const cont = this.getCont(contA)
return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value))
}
yieldWith(value: Exit.Exit<any, any> | (() => void)): Yield {
this._yielded = value
return Yield
@@ -783,9 +772,6 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
resumed = true
})
}
children(): Set<Fiber.Fiber<any, any>> {
return (this._children ??= new Set())
}
pipe() {
return pipeArguments(this, arguments)
}
@@ -805,10 +791,6 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
}
this.cache = cache
}
get currentSpanLocal(): Tracer.Span | undefined {
const span = this.cache.span
return span?._tag === "Span" ? span : undefined
}
}
const makeFiberContextCache = (context: Context.Context<never>): Fiber.Fiber.Cache => {
@@ -842,6 +824,23 @@ const deferredInterruptCont: any = {
// must be a power of two
const maxInlineSteps = 32
// Passes a success value straight to the next continuation instead of
// returning an Exit for the run loop to unwrap. Each call counts as an
// operation, and every `maxInlineSteps`th call returns an Exit instead, so
// continuations calling continuations never nest deeper than that.
const succeedWith = (fiber: FiberImpl, value: unknown): Primitive | Yield => {
if ((++fiber.currentOpCount & (maxInlineSteps - 1)) === 0) {
return exitSucceed(value) as any
}
const cont = fiber.getCont(contA)
return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value))
}
const currentSpanLocal = (fiber: FiberImpl): Tracer.Span | undefined => {
const span = fiber.cache.span
return span?._tag === "Span" ? span : undefined
}
const fiberMiddleware = {
interruptChildren: undefined as
| ((fiber: FiberImpl) => Effect.Effect<void> | undefined)
@@ -1579,7 +1578,7 @@ const returnPayload = function(this: { readonly payload: any }) {
return this.payload
}
const succeedPayload = function(this: { readonly payload: any }, _value: unknown, fiber: FiberImpl) {
return fiber.succeedWith(this.payload)
return succeedWith(fiber, this.payload)
}
// V8 includes the property name of a stored continuation in its stack trace.
// Other engines need an explicit frame for the stack cleaner to cut at.
@@ -1600,7 +1599,7 @@ const continuationMarksStack = (() => {
})()
const mapCont = function(this: { readonly payload: any }, value: any, fiber: FiberImpl) {
const f = this.payload
return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value)))
return succeedWith(fiber, continuationMarksStack ? f(value) : internalCall(() => f(value)))
}
const andThenCont = function(this: { readonly payload: any }, value: any) {
const f = this.payload
@@ -3618,7 +3617,8 @@ OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto
// payload and call it from the prototype, so no closure is built per call.
const matchSuccess = function(this: any, value: any, fiber: FiberImpl) {
const handlers = this.payload
return fiber.succeedWith(
return succeedWith(
fiber,
continuationMarksStack ? handlers.onSuccess(value) : internalCall(() => handlers.onSuccess(value))
)
}
@@ -3646,13 +3646,15 @@ const MatchImpl = makeMatch("Match", function(cause, fiber) {
const error = findRecoverableError(cause)
if (Result.isFailure(error)) return failCause(error.failure) as any
const handlers = this.payload
return fiber.succeedWith(
return succeedWith(
fiber,
continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))
)
})
const MatchCauseImpl = makeMatch("MatchCause", function(cause, fiber) {
const handlers = this.payload
return fiber.succeedWith(
return succeedWith(
fiber,
continuationMarksStack ? handlers.onFailure(cause) : internalCall(() => handlers.onFailure(cause))
)
})
@@ -3814,10 +3816,10 @@ const exitPrimitive: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Ex
return this[args] as any
},
[contA](value, fiber, exit) {
return fiber.succeedWith(exit ?? exitSucceed(value))
return succeedWith(fiber, exit ?? exitSucceed(value))
},
[contE](cause, fiber, exit) {
return fiber.succeedWith(exit ?? exitFailCause(cause))
return succeedWith(fiber, exit ?? exitFailCause(cause))
}
})
@@ -5558,7 +5560,8 @@ export const forkUnsafe = <FA, FE, A, E, R>(
const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible
const child = new FiberImpl<A, E>(parentRuntime.context, interruptible)
if (!daemon) {
parentRuntime.children().add(child)
const children = parentRuntime._children ??= new Set()
children.add(child)
child._parent = parentRuntime
}
if (immediate) {
@@ -6308,7 +6311,7 @@ export const annotateCurrentSpan: {
(values: Record<string, unknown>): Effect.Effect<void>
} = (...args: [Record<string, unknown>] | [key: string, value: unknown]) =>
withFiber((fiber) => {
const span = fiber.currentSpanLocal
const span = currentSpanLocal(fiber)
if (span && span.status._tag !== "Ended") {
if (args.length === 1) {
for (const [key, value] of Object.entries(args[0])) {
@@ -6323,7 +6326,7 @@ export const annotateCurrentSpan: {
/** @internal */
export const currentSpan: Effect.Effect<Tracer.Span, Cause.NoSuchElementError> = withFiber((fiber) => {
const span = fiber.currentSpanLocal
const span = currentSpanLocal(fiber)
return span ? succeed(span) : fail(new NoSuchElementError())
})