Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

Layout time doubles per nesting level: `computeMinContentMainSize` recurses twice per child

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

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

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
68/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
静か
技術スタック
cpp
領域
performance

調査の方向性

yoga/algorithm/CalculateLayout.cpp の computeMinContentMainSize と、その呼び出し元である computeAutoMinMainSize から始めます。既存のレイアウト動作と提案された結合トラバーサルを比較し、issue で説明されている差分ハーネスを使って、深くネストされたレイアウトが線形にスケールし、ジオメトリが変わらないことを検証します。

索引モデルが issue の本文から書いたものです。

説明

Summary

computeMinContentMainSize in yoga/algorithm/CalculateLayout.cpp is a
per-axis function, so the container branch recurses into every child twice
-- once for the node's main axis and once for its cross axis:

float childMain = computeMinContentMainSize(
    child, nodeMainAxis, direction, ownerWidth, ownerHeight);
...
float childCross = computeMinContentMainSize(
    child, nodeCrossAxis, direction, ownerWidth, ownerHeight);

Each call re-walks that child's entire subtree and keeps a single component,
so a chain of flex containers costs T(d) = 2*T(d-1) -- i.e. O(2^depth).
Nothing memoizes it: the recursion does no layout writes and does not go
through the layout cache, so the cost is invisible to the cache counters.

This is reachable from ordinary markup. computeAutoMinMainSize calls it for
every in-flow flex item whenever the config does not set
Errata::MinSizeUndefinedInsteadOfAuto -- i.e. under the modern default --
which is the CSS Flexbox §4.5 automatic minimum size path.

Repro

Plain nested flex rows, no measure functions, no custom config beyond
YGErrataNone, one concrete leaf at the bottom:

#include <yoga/Yoga.h>
#include <chrono>
#include <cstdio>
#include <vector>

static double timeDepth(int depth) {
  YGConfigRef config = YGConfigNew();
  YGConfigSetErrata(config, YGErrataNone);

  std::vector<YGNodeRef> chain;
  YGNodeRef root = YGNodeNewWithConfig(config);
  YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);
  YGNodeStyleSetWidth(root, 800);
  YGNodeStyleSetHeight(root, 600);
  chain.push_back(root);

  for (int i = 0; i < depth; i++) {
    YGNodeRef n = YGNodeNewWithConfig(config);
    YGNodeStyleSetFlexDirection(n, YGFlexDirectionRow);
    YGNodeInsertChild(chain.back(), n, 0);
    chain.push_back(n);
  }
  YGNodeRef leaf = YGNodeNewWithConfig(config);
  YGNodeStyleSetWidth(leaf, 20);
  YGNodeStyleSetHeight(leaf, 20);
  YGNodeInsertChild(chain.back(), leaf, 0);

  auto t0 = std::chrono::steady_clock::now();
  YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR);
  auto t1 = std::chrono::steady_clock::now();
  YGNodeFreeRecursive(root);
  YGConfigFree(config);
  return std::chrono::duration<double>(t1 - t0).count();
}

int main() {
  for (int d : {16, 18, 20, 22, 24, 26}) {
    std::printf("%3d %8.3f s\n", d, timeDepth(d));
    std::fflush(stdout);
  }
}

main@433d463, clang -O2 (Apple M-series), median of 5 runs:

depth layout time vs previous shown
16 0.004 s
18 0.017 s 4.2x
20 0.065 s 3.8x
22 0.264 s 4.1x
24 1.055 s 4.0x
26 4.233 s 4.0x

Steady ~4x per two levels, i.e. ~2x per level -- the 2^depth signature.
Extrapolating the same factor, depth 30 lands around a minute, which reads as
a hang rather than as slowness.

Proposed fix

Compute both components in a single walk. Each subtree then costs exactly one
recursion and the per-pass cost goes back to linear.

Semantics are preserved point for point:

  • static per-axis values still win, and when both are defined the function
    still returns without recursing (matching today's early return);
  • leaves still measure once per axis and still add their own padding/border;
  • each child's contribution is projected onto the parent's main/cross axes,
    which is exactly what the two separate calls produced.

The shape of the change, condensed (full patch in a PR if you want it):

-static float computeMinContentMainSize(
-    yoga::Node* const node,
-    const FlexDirection requestedAxis,
-    const Direction ownerDirection,
-    const float ownerWidth,
-    const float ownerHeight) {
-  const bool wantRow = isRow(requestedAxis);
-  const FloatOptional staticMin =
-      wantRow ? node->getMinContentWidth() : node->getMinContentHeight();
-  if (staticMin.isDefined()) {
-    return staticMin.unwrap();
-  }
+struct MinContentSize {
+  float width;
+  float height;
+};
+
+static MinContentSize computeMinContentSize(
+    yoga::Node* const node,
+    const Direction ownerDirection,
+    const float ownerWidth,
+    const float ownerHeight) {
+  const FloatOptional staticW = node->getMinContentWidth();
+  const FloatOptional staticH = node->getMinContentHeight();
+  // Both pinned -> still no recursion at all, as before.
+  if (staticW.isDefined() && staticH.isDefined()) {
+    return {staticW.unwrap(), staticH.unwrap()};
+  }

   // ... measure-func branch: measure once per axis, add own padding/border
   //     (unchanged, just returning both components)

   for (size_t i = 0; i < node->getChildCount(); i++) {
     ...
-    float childMain = computeMinContentMainSize(
-        child, nodeMainAxis, direction, ownerWidth, ownerHeight);
+    // One recursion per child, then project onto this node's axes.
+    const MinContentSize childSize =
+        computeMinContentSize(child, direction, ownerWidth, ownerHeight);
+
+    float childMain = nodeMainIsRow ? childSize.width : childSize.height;
     childMain += child->style().computeMarginForAxis(nodeMainAxis, ownerWidth);
-
-    float childCross = computeMinContentMainSize(
-        child, nodeCrossAxis, direction, ownerWidth, ownerHeight);
+    float childCross = nodeMainIsRow ? childSize.height : childSize.width;
     childCross +=
         child->style().computeMarginForAxis(nodeCrossAxis, ownerWidth);

     mainTotal += childMain;
     crossMax = std::max(crossMax, childCross);
   }

   // ... padding/border added per axis (unchanged)
-  return wantRow ? widthMin : heightMin;
+  return {
+      staticW.isDefined() ? staticW.unwrap() : widthMin,
+      staticH.isDefined() ? staticH.unwrap() : heightMin};
 }

The single caller in computeAutoMinMainSize then projects instead of
picking an axis up front:

-  const FloatOptional contentMain = FloatOptional{computeMinContentMainSize(
-      child, mainAxis, direction, ownerWidth, ownerHeight)};
+  const MinContentSize contentSize =
+      computeMinContentSize(child, direction, ownerWidth, ownerHeight);
+  const FloatOptional contentMain =
+      FloatOptional{isRow(mainAxis) ? contentSize.width : contentSize.height};

One subtlety worth calling out: when only one axis has a static
min-content value the function must still recurse for the other, so the
static value is applied per-axis at the return sites rather than as a
single early exit. That matches what the two per-axis calls did (one
short-circuited, the other recursed).

With the patch, same machine and harness:

depth 26 40 60 100 200
layout time 0.00002 s 0.0001 s 0.0001 s 0.0003 s 0.0009 s

Depth 26 goes from 4.2 s to under a tenth of a millisecond, and depth 200 --
far past where stock yoga stops finishing at all -- costs under a millisecond.

Results are unchanged. I ran a differential harness over 300
pseudo-randomly generated trees (mixed row/column, percent and fixed sizes,
flex grow/shrink, min/max constraints, padding/margin/border, aspect-ratio,
wrap, overflow:scroll, absolute children, both LTR and RTL), dumping
left/top/width/height for every node -- 17,094 lines of geometry, byte
identical
between stock and patched builds.

Happy to open a PR with the change plus the differential harness as a test if
that shape is useful; let me know if you would rather have it as a benchmark
under benchmark/ or a gtest case.

主要言語
C++
スター
18.9k
フォーク
1.6k
平均マージ
18時間 48分
マージ済み PR(30日)
4

環境構築

はじめの一歩

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

react/yoga のほかの issue

react/yoga の issue をすべて見る

似ている issue

C++ の issue をもっと見る

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

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