Sequential Effect.forEach allocates an iterator result per item and suspends twice
Los mantenedores suelen responder en 1 día
Evaluación
Este issue todavía no se ha evaluado.
Descripción
What happens
Effect.forEach without concurrency (and Effect.all over a tuple, which uses it) walks its input with iterable[Symbol.iterator](), so every item allocates an iterator result object, about 40 B per item, even for a plain array. It also wraps the work in suspend twice: once in forEach to resolve the concurrency and again in forEachSequential. With discard: true the per-item allocation is the only thing that grows with the input: 100 items cost 5.0 KB. An empty array costs about 950 B.
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; the byte figures are stable.
| Case | main | with change |
|---|---|---|
Effect.forEach, 0 items |
956 B, 231 ns | 461 B, 115 ns |
Effect.forEach, 1 item |
1,135 B, 252 ns | 911 B, 226 ns |
Effect.forEach, 10 items |
1,504 B, 558 ns | 917 B, 483 ns |
Effect.forEach, 100 items |
7,326 B, 3,240 ns | 3,137 B, 2,600 ns |
Effect.forEach, 10 items, discard |
1,427 B, 590 ns | 708 B, 493 ns |
Effect.forEach, 100 items, discard |
5,043 B, 3,025 ns | 746 B, 2,679 ns |
Effect.forEach, 10 items of Effect.succeed |
1,585 B, 622 ns | 913 B, 528 ns |
Effect.all, tuple of 3 |
1,319 B, 405 ns | 927 B, 331 ns |
Effect.forEach over a Set of 10 |
1,578 B, 619 ns | 1,394 B, 602 ns |
Reproduction
Save the two 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 for-each-sequential.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)
}
for-each-sequential.repro.ts
/**
* Effect.forEach without concurrency: fixed cost and cost per item.
*
* node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 for-each-sequential.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 done = Effect.succeed(1)
const items = (count: number) => Array.from({ length: count }, (_, i) => i)
const empty = items(0)
const one = items(1)
const ten = items(10)
const hundred = items(100)
const set = new Set(ten)
measureEffect("Effect.forEach, 0 items", N, () => Effect.forEach(empty, () => step), id)
measureEffect("Effect.forEach, 1 item", N, () => Effect.forEach(one, () => step), id)
measureEffect("Effect.forEach, 10 items", N, () => Effect.forEach(ten, () => step), id)
measureEffect("Effect.forEach, 100 items", N, () => Effect.forEach(hundred, () => step), id)
measureEffect("Effect.forEach, 10 items, discard", N, () => Effect.forEach(ten, () => step, { discard: true }), id)
measureEffect("Effect.forEach, 100 items, discard", N, () => Effect.forEach(hundred, () => step, { discard: true }), id)
measureEffect("Effect.forEach, 10 items of Effect.succeed", N, () => Effect.forEach(ten, () => done), id)
measureEffect("Effect.all, tuple of 3", N, () => Effect.all([step, step, step]), id)
measureEffect("Effect.forEach over a Set of 10", N, () => Effect.forEach(set, () => step), id)
Cause
forEach and forEachSequential in packages/effect/src/internal/effect.ts.
Possible fix
Let forEachSequential start the loop directly, since it already runs inside the suspend of forEach, and read a plain array by index. An array that overrides Symbol.iterator, and any other iterable, keeps the iterator path.
Context
Found by measuring the Effect APIs that a production Node.js service on effect 4.0.1 calls most, after sampling heap profiles of that service showed these call sites. A pull request with the change and tests follows.
- Lenguaje dominante
- TypeScript
- Estrellas
- 16.7k
- Forks
- 808
- Merge medio
- 21 h 22 min
- PR fusionados (30 d)
- 486
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de Effect-TS/effect
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
`@effect/ui-native` (Effect-TS/ui): `kit/VirtualList` `list` part widens `R` to `any`, poisoning enclosing componentsPosiblemente ocupada @effect-bot la tomó hoy. Abierto
Effect-TS/effect#11097 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
`@effect/ui-native` (Effect-TS/ui): Controlled `input` rejected-edit restore never calls `host.commit()`Posiblemente ocupada @effect-bot la tomó hoy. Abierto
Effect-TS/effect#11096 · 1 asignado ·
Los mantenedores suelen responder en 1 día
Todos los issues de Effect-TS/effect
Issues similares
-
check:failed streams:edit
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
iptv-org/iptv#60585 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 67/100
Los mantenedores suelen responder en 1 día
-
[Bug]: Critical path skips a child span that ends exactly when the next one startsPosiblemente ocupada @Piyush4801 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
jaegertracing/jaeger-ui#4865 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 90/100
anthropics/claude-code#112972 ·
-
Type: Improvement
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día