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

オープン
#11,066 コメント 0 件 リアクション 0 件 担当者 1 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@effect-bot がすでに取り組んでいます。

2026年11月29日 から。

  • #11067 @andymac4182 による — オープン

評価

この issue はまだ評価されていません。

説明

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.

主要言語
TypeScript
スター
16.7k
フォーク
808
平均マージ
21時間 22分
マージ済み PR(30日)
486

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

Effect-TS/effect のほかの issue

Effect-TS/effect の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。