Effect.fn captures a call-site stack on every call, which is most of its cost; could it be made optional?
Maintainer thường phản hồi trong vòng 1 ngày
Đánh giá
Issue này chưa được đánh giá.
Mô tả
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 ofcaptureStackTrace: falseonEffect.withSpan, so that a hot function can opt out on its own; or - a process-wide switch that
makeFnreads 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.
- Ngôn ngữ chính
- TypeScript
- Star
- 16.7k
- Fork
- 808
- Merge trung bình
- 21 giờ 22 phút
- Pull request đã merge (30 ngày)
- 486
Chuẩn bị môi trường
Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của Effect-TS/effect
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
`@effect/ui-native` (Effect-TS/ui): `kit/VirtualList` `list` part widens `R` to `any`, poisoning enclosing componentsCó thể đã có người làm @effect-bot đã nhận hôm nay. Đang mở
Effect-TS/effect#11097 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
`@effect/ui-native` (Effect-TS/ui): Controlled `input` rejected-edit restore never calls `host.commit()`Có thể đã có người làm @effect-bot đã nhận hôm nay. Đang mở
Effect-TS/effect#11096 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của Effect-TS/effect
Issue tương tự
-
check:failed streams:edit
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
iptv-org/iptv#60585 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 67/100
Maintainer thường phản hồi trong vòng 1 ngày
-
[Bug]: Critical path skips a child span that ends exactly when the next one startsCó thể đã có người làm @Piyush4801 đã nhận hôm nay. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
jaegertracing/jaeger-ui#4865 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
bug
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 90/100
anthropics/claude-code#112972 ·
-
Type: Improvement
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
Maintainer thường phản hồi trong vòng 1 ngày