Effect.fn captures a call-site stack on every call, which is most of its cost; could it be made optional?

未关闭
#11,070 0 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 1 天内回复

@effect-bot 已经在做这个了。

开始于 2026年11月29日。

  • #11082 来自 @effect-bot —— 未关闭

评估

这个 Issue 还没有评估数据。

描述

What happens

Every call of a function made with Effect.fn, with or without a span name, runs new Error() at a stack trace limit of two so that a later failure can show where the function was called from. That capture is about two thirds of the time of the call. An Effect.fn call with no span costs about 1.0 µs and 2.0 KB, against 0.2 µs and 0.6 KB for the same body under Effect.fnUntraced; with Error.stackTraceLimit = 0, which skips the capture, it costs about 0.5 µs.

Nested calls pay it at every level: six nested Effect.fn calls take 5.8 µs, 2.7 µs without the capture, and 0.7 µs untraced.

Today the only ways to avoid it are Effect.fnUntraced, which also drops the definition frame and the span, or setting Error.stackTraceLimit = 0 for the whole process.

Measurements

Measured on main at ddc5b58 (4.1.7), Node.js 24.22, Apple silicon. Bytes are heap growth per operation with no collection during the loop, median of seven rounds. Timings were taken on a machine under other load and vary by about 20% between runs.

Case default Error.stackTraceLimit = 0
new Error() at a limit of two (for scale) 161 B, 368 ns 48 B, 122 ns
Effect.fnUntraced call 600 B, 192 ns 598 B, 192 ns
Effect.fn call, no span 2,047 B, 1,211 ns 1,869 B, 524 ns
Effect.fn call, no span, caller 20 frames deep 2,085 B, 1,337 ns 1,933 B, 607 ns
Effect.fn("named") call 4,388 B, 1,960 ns 3,936 B, 1,235 ns
constructing the Effect.fn call only, not running it 784 B, 441 ns 639 B, 58 ns
6 nested Effect.fn calls, no span 12,355 B, 5,782 ns 10,470 B, 2,689 ns
6 nested Effect.fnUntraced calls 3,173 B, 729 ns 3,170 B, 806 ns

Reproduction

Save the files below in packages/effect/alloc-repro/ in a checkout of this repository and run:

node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-call-site.repro.ts
node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-nested.repro.ts
harness.ts
/**
 * Shared measurement helper: bytes and nanoseconds per operation.
 *   node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 <file>.ts
 * Heap growth is read across N operations with a forced GC before and a young
 * generation large enough that no collection runs in between: the
 * operation count is cut so one round stays under BUDGET bytes.
 */
import * as Effect from "effect/Effect"

const gc = (globalThis as { gc?: () => void }).gc
if (gc === undefined) throw new Error("run with --expose-gc")

export const ROUNDS = 7
const BUDGET = 256 * 1024 * 1024
const sized = (n: number, probeBytes: number) => Math.max(50, Math.min(n, Math.floor(BUDGET / Math.max(probeBytes, 1))))

const median = (xs: Array<number>) => xs.toSorted((a, b) => a - b)[Math.floor(xs.length / 2)]

export const row = (label: string, bytes: number, ns: number) =>
  console.log(`${label.padEnd(64)} ${bytes.toFixed(0).padStart(8)} B/op ${ns.toFixed(0).padStart(8)} ns/op`)

/** Measures a synchronous operation. */
export const measureSync = (label: string, n: number, op: (i: number) => unknown) => {
  for (let i = 0; i < 5000; i++) op(i)
  gc()
  const probe = process.memoryUsage().heapUsed
  for (let i = 0; i < 50; i++) op(i)
  n = sized(n, (process.memoryUsage().heapUsed - probe) / 50)
  const bytes: Array<number> = []
  const nanos: Array<number> = []
  for (let r = 0; r < ROUNDS; r++) {
    gc()
    const before = process.memoryUsage().heapUsed
    const start = process.hrtime.bigint()
    for (let i = 0; i < n; i++) op(i)
    const end = process.hrtime.bigint()
    bytes.push((process.memoryUsage().heapUsed - before) / n)
    nanos.push(Number(end - start) / n)
  }
  row(label, median(bytes), median(nanos))
  return median(bytes)
}

/** Measures an Effect run `n` times inside one fiber, so the fiber context is the one supplied by `wrap`. */
export const measureEffect = <E, R>(
  label: string,
  n: number,
  op: (i: number) => Effect.Effect<unknown, E, R>,
  wrap: (self: Effect.Effect<void, E, R>) => Effect.Effect<void, E, never>
) => {
  const bytes: Array<number> = []
  const nanos: Array<number> = []
  const loop = (count: number) =>
    Effect.gen(function*() {
      for (let i = 0; i < count; i++) yield* op(i)
    })
  const program = Effect.gen(function*() {
    yield* loop(5000)
    gc()
    const probe = process.memoryUsage().heapUsed
    yield* loop(50)
    n = sized(n, (process.memoryUsage().heapUsed - probe) / 50)
    for (let r = 0; r < ROUNDS; r++) {
      gc()
      const before = process.memoryUsage().heapUsed
      const start = process.hrtime.bigint()
      yield* loop(n)
      const end = process.hrtime.bigint()
      bytes.push((process.memoryUsage().heapUsed - before) / n)
      nanos.push(Number(end - start) / n)
    }
  })
  Effect.runSync(wrap(program))
  row(label, median(bytes), median(nanos))
  return median(bytes)
}
fn-call-site.repro.ts
/**
 * Effect.fn: cost of the call-site stack capture taken on every call.
 *
 *   node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-call-site.repro.ts
 */
import * as Effect from "effect/Effect"
import { measureEffect, measureSync } from "./harness.ts"

const N = 20000
const id = <A, E>(self: Effect.Effect<A, E>) => self
const step = Effect.sync(() => 1)
const untraced = Effect.fnUntraced(function*(n: number) {
  return (yield* step) + n
})
const unnamed = Effect.fn(function*(n: number) {
  return (yield* step) + n
})
const named = Effect.fn("named")(function*(n: number) {
  return (yield* step) + n
})
// A caller a few frames deep, as application code is.
const deep = (f: (n: number) => Effect.Effect<number>, depth: number) => {
  const go = (n: number, d: number): Effect.Effect<number> => d === 0 ? f(n) : go(n, d - 1)
  return (n: number) => go(n, depth)
}

const limit = Error.stackTraceLimit
const all = (label: string) => {
  measureSync(`${label}: new Error() at limit 2 (for scale)`, N, () => {
    const prev = Error.stackTraceLimit
    Error.stackTraceLimit = prev === 0 ? 0 : 2
    const error = new Error()
    Error.stackTraceLimit = prev
    return error
  })
  measureEffect(`${label}: Effect.fnUntraced call`, N, (i) => untraced(i), id)
  measureEffect(`${label}: Effect.fn call, no span`, N, (i) => unnamed(i), id)
  measureEffect(`${label}: Effect.fn call, no span, 20 frames deep`, N, deep(unnamed, 20), id)
  measureEffect(`${label}: Effect.fn("named") call`, N, (i) => named(i), id)
  measureSync(`${label}: constructing Effect.fn call only`, N, (i) => unnamed(i))
  measureSync(`${label}: constructing Effect.fnUntraced call only`, N, (i) => untraced(i))
}
all("default")
Error.stackTraceLimit = 0
all("stackTraceLimit 0")
Error.stackTraceLimit = limit
fn-nested.repro.ts
/**
 * Effect.fn: cost of a traced call, alone and nested, against Effect.fnUntraced.
 * The stack capture is switched off for the second half so that the rest of the
 * call can be read on its own.
 *
 *   node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-nested.repro.ts
 */
import * as Effect from "effect/Effect"
import { measureEffect } from "./harness.ts"

const N = 20000
const id = <A, E>(self: Effect.Effect<A, E>) => self
const step = Effect.sync(() => 1)
const untraced = Effect.fnUntraced(function*(n: number) {
  return (yield* step) + n
})
const unnamed = Effect.fn(function*(n: number) {
  return (yield* step) + n
})
const named = Effect.fn("named")(function*(n: number) {
  return (yield* step) + n
})
const nest = (
  make: (body: (n: number) => Generator<Effect.Effect<number>, number, number>) => (n: number) => Effect.Effect<number>,
  depth: number
) => {
  let f = make(function*(n) {
    return (yield* step) + n
  })
  for (let i = 1; i < depth; i++) {
    const inner = f
    f = make(function*(n) {
      return yield* inner(n)
    })
  }
  return f
}
const untraced6 = nest((body) => Effect.fnUntraced(body), 6)
const unnamed6 = nest((body) => Effect.fn(body), 6)
const named6 = nest((body) => Effect.fn("named")(body), 6)
const withSpan = (n: number) => Effect.withSpan(untraced(n), "span", { captureStackTrace: false })

const limit = Error.stackTraceLimit
for (const label of ["default", "stackTraceLimit 0"]) {
  if (label !== "default") Error.stackTraceLimit = 0
  measureEffect(`${label}: Effect.fnUntraced call`, N, (i) => untraced(i), id)
  measureEffect(`${label}: Effect.fn call, no span`, N, (i) => unnamed(i), id)
  measureEffect(`${label}: Effect.fn("named") call`, N, (i) => named(i), id)
  measureEffect(`${label}: Effect.withSpan, no stack capture`, N, withSpan, id)
  measureEffect(`${label}: 6 nested Effect.fnUntraced calls`, N, (i) => untraced6(i), id)
  measureEffect(`${label}: 6 nested Effect.fn calls, no span`, N, (i) => unnamed6(i), id)
  measureEffect(`${label}: 6 nested Effect.fn("named") calls`, N, (i) => named6(i), id)
}
Error.stackTraceLimit = limit

Cause

makeFn in packages/effect/src/internal/effect.ts: setStackTraceLimit(2); callError = new globalThis.Error(); setStackTraceLimit(prevLimit) on every call.

Question

Would you consider a way to keep Effect.fn (the definition frame, and the span when it is named) without the per-call capture? Two shapes that would work for us:

  • an option on Effect.fn, in the spirit of captureStackTrace: false on Effect.withSpan, so that a hot function can opt out on its own; or
  • a process-wide switch that makeFn reads at call time.

The stack frame would then carry only the definition location. We have not opened a pull request because the API is yours to choose; we are happy to write one for whichever shape you prefer.

Context

Found from CPU profiles of a production Node.js service on effect 4.0.1 with about 2,700 Effect.fn definitions, where the Effect.fn wrapper and addSpanStackTrace together take about 1% of non-idle CPU before counting the garbage they create.

主要语言
TypeScript
星标
16.7k
派生
808
平均合并
21 小时 22 分钟
30 天内合并 PR
486

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

Effect-TS/effect 的其他 Issue

查看 Effect-TS/effect 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。