Sequential Effect.forEach allocates an iterator result per item and suspends twice

Abierto
#11,066 0 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@effect-bot ya está trabajando en esto.

Desde el 29/11/2026.

  • #11067 de @andymac4182 — abierto

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

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Effect-TS/effect

Todos los issues de Effect-TS/effect

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.