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

Đang mở
#11,066 0 bình luận 0 reaction 1 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@effect-bot đang làm issue này rồi.

Từ ngày 29/11/2026.

  • #11067 của @andymac4182 — đang mở

Đánh giá

Issue này chưa được đánh giá.

Mô tả

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.

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

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của Effect-TS/effect

Tất cả issue của Effect-TS/effect

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.