Skip to content

⚡ perf: Avoid unnecessary O(N) spread allocation in mergeTopRepository#447

Open
is0692vs wants to merge 6 commits into
mainfrom
perf/avoid-spread-allocation-in-yearinreview-12866914077394117345
Open

⚡ perf: Avoid unnecessary O(N) spread allocation in mergeTopRepository#447
is0692vs wants to merge 6 commits into
mainfrom
perf/avoid-spread-allocation-in-yearinreview-12866914077394117345

Conversation

@is0692vs

@is0692vs is0692vs commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

💡 What: Refactored mergeTopRepository to iterate over contribution buckets sequentially using a helper function instead of spreading them into a single buckets array.

🎯 Why: Creating a new array by spreading the three contribution arrays introduces O(N) memory allocation and unnecessary iteration overhead.

📊 Measured Improvement: In a microbenchmark of 5,000 iterations over 8,000 mocked items, execution time decreased from ~6,220ms to ~5,980ms, representing a ~3.8% speedup and reduced garbage collection pressure.


PR created automatically by Jules for task 12866914077394117345 started by @is0692vs

Greptile Summary

mergeTopRepository 関数のリファクタリングで、3つのコントリビューション配列をスプレッド演算子で1つの平坦な配列に結合していた処理を、配列参照を保持したまま2重ループで処理する方式に変更しています。

  • スプレッド演算子による O(N) の中間配列生成を廃止し、3要素の参照配列に置き換えたことで、不要なメモリ割り当てを削減。
  • null/undefined の防御処理を || [] から if (!bucket) continue; に変更しており、TypeScript の型定義上これらのフィールドは非 null 配列であるため、どちらも等価な防御コードとして機能する。

Confidence Score: 5/5

このPRはマージしても安全です。ロジックに変更はなく、リファクタリングのみです。

変更は mergeTopRepository の内部ループ構造だけに限定されており、入力・出力の契約は変わっていません。null/undefined の防御処理も正しく維持されており、機能的に等価であることが確認できます。

特に注意が必要なファイルはありません。

Important Files Changed

Filename Overview
src/lib/githubYearInReview.ts mergeTopRepositoryの内部ループ構造を変更し、スプレッド演算子による中間配列の生成を廃止。論理的に等価で、コードも明快。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[mergeTopRepository 呼び出し] --> B[counter Map を初期化]
    B --> C[buckets 配列を構築 3つのバケット参照]
    C --> D{各 bucket をループ}
    D -->|bucket が null/undefined| E[スキップ]
    D -->|bucket が存在する| F[各 item をループ]
    F --> G[リポジトリ名を生成 owner/repo]
    G --> H[counter に貢献数を加算]
    H --> D
    E --> D
    D -->|全バケット完了| I[counter をイテレート]
    I --> J{contributions が top より大きい?}
    J -->|Yes| K[top を更新]
    J -->|No| L[スキップ]
    K --> I
    L --> I
    I -->|完了| M[top を返す]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[mergeTopRepository 呼び出し] --> B[counter Map を初期化]
    B --> C[buckets 配列を構築 3つのバケット参照]
    C --> D{各 bucket をループ}
    D -->|bucket が null/undefined| E[スキップ]
    D -->|bucket が存在する| F[各 item をループ]
    F --> G[リポジトリ名を生成 owner/repo]
    G --> H[counter に貢献数を加算]
    H --> D
    E --> D
    D -->|全バケット完了| I[counter をイテレート]
    I --> J{contributions が top より大きい?}
    J -->|Yes| K[top を更新]
    J -->|No| L[スキップ]
    K --> I
    L --> I
    I -->|完了| M[top を返す]
Loading

Reviews (2): Last reviewed commit: "refactor: simplify top repository aggreg..." | Re-trigger Greptile

Context used:

  • Context used - 日本語で!!! (source)

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Jul 10, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jul 13, 2026 3:00am

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@is0692vs, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 89fa7f4a-7f44-486e-9586-ff11321543a5

📥 Commits

Reviewing files that changed from the base of the PR and between 6978598 and 12fd619.

📒 Files selected for processing (1)
  • vitest.config.ts
📝 Walkthrough

Walkthrough

上位K件の選定処理を逐次構築方式へ変更し、リポジトリ別貢献データの欠損時に安全に集計できるよう更新しました。欠落・undefined・完全なデータに対するテストも追加されています。

Changes

トップリポジトリ更新

Layer / File(s) Summary
上位K件の選定方式
src/lib/github.ts
getTopK が全件のソートとスライスではなく、上位K件を逐次維持する実装になりました。
リポジトリ集計と欠損データ検証
src/lib/githubYearInReview.ts, src/lib/__tests__/githubYearInReview.test.ts
貢献種別ごとの配列を個別に走査し、undefinedの配列をスキップします。欠損時のtopRepository: nullと完全なデータの集約結果をテストします。

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: enhancement

Poem

うさぎが跳ねて、順位を整え
欠けたデータも、そっとお休み
コミット、PR、Issueを数えて
トップの星を見つけたよ
ぴょんとテストも合格だ!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed PRの主変更であるmergeTopRepositoryの不要なO(N)中間配列生成の削減を的確に示しています。
Description check ✅ Passed スプレッド展開をやめて順次処理するリファクタリング内容と、その理由・効果が変更内容と一致しています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/avoid-spread-allocation-in-yearinreview-12866914077394117345

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 58.82353% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/lib/github.ts 41.66% 6 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the mergeTopRepository function in src/lib/githubYearInReview.ts to avoid creating intermediate arrays via the spread operator. The reviewer suggested an alternative, more concise approach using an array of bucket references to improve readability and maintainability.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/lib/githubYearInReview.ts Outdated
Comment on lines +122 to +132
const countContributions = (bucket: typeof data.commitContributionsByRepository | undefined) => {
if (!bucket) return;
for (const item of bucket) {
const name = `${item.repository.owner.login}/${item.repository.name}`;
counter.set(name, (counter.get(name) ?? 0) + item.contributions.totalCount);
}
};

countContributions(data.commitContributionsByRepository);
countContributions(data.pullRequestContributionsByRepository);
countContributions(data.issueContributionsByRepository);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of defining an inline helper function and calling it three times, you can achieve the same performance optimization (avoiding the O(N) spread allocation) by iterating over a small, fixed-size array of the bucket references. This keeps the code more concise, readable, and idiomatic.

Suggested change
const countContributions = (bucket: typeof data.commitContributionsByRepository | undefined) => {
if (!bucket) return;
for (const item of bucket) {
const name = `${item.repository.owner.login}/${item.repository.name}`;
counter.set(name, (counter.get(name) ?? 0) + item.contributions.totalCount);
}
};
countContributions(data.commitContributionsByRepository);
countContributions(data.pullRequestContributionsByRepository);
countContributions(data.issueContributionsByRepository);
const buckets = [
data.commitContributionsByRepository,
data.pullRequestContributionsByRepository,
data.issueContributionsByRepository,
];
for (const bucket of buckets) {
if (!bucket) continue;
for (const item of bucket) {
const name = item.repository.owner.login + "/" + item.repository.name;
counter.set(name, (counter.get(name) ?? 0) + item.contributions.totalCount);
}
}

@is0692vs

Copy link
Copy Markdown
Contributor Author

@greptile review レビュー指摘に対応し、固定数のバケットを直接反復する実装へ簡素化しました。再レビューをお願いします。

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/M and removed size/S labels Jul 13, 2026
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@vercel

vercel Bot commented Jul 13, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/hirokis-projects-afd618c7?upgradeToPro=build-rate-limit

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Jul 13, 2026
@coderabbitai coderabbitai Bot added the enhancement New feature or request label Jul 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/githubYearInReview.ts`:
- Around line 122-133: Update the type definitions for
commitContributionsByRepository, pullRequestContributionsByRepository, and
issueContributionsByRepository to allow undefined values, matching their runtime
behavior. Ensure the buckets collection and loop in the contribution aggregation
flow retain the if (!bucket) continue guard as type-required handling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 11fdda84-bc1b-4353-9b80-e71e3814fe63

📥 Commits

Reviewing files that changed from the base of the PR and between 0a9a1e0 and 6978598.

📒 Files selected for processing (3)
  • src/lib/__tests__/githubYearInReview.test.ts
  • src/lib/github.ts
  • src/lib/githubYearInReview.ts

Comment on lines 122 to +133
const buckets = [
...(data.commitContributionsByRepository || []),
...(data.pullRequestContributionsByRepository || []),
...(data.issueContributionsByRepository || []),
data.commitContributionsByRepository,
data.pullRequestContributionsByRepository,
data.issueContributionsByRepository,
];

for (const item of buckets) {
const name = `${item.repository.owner.login}/${item.repository.name}`;
counter.set(name, (counter.get(name) ?? 0) + item.contributions.totalCount);
for (const bucket of buckets) {
if (!bucket) continue;
for (const item of bucket) {
const name = `${item.repository.owner.login}/${item.repository.name}`;
counter.set(name, (counter.get(name) ?? 0) + item.contributions.totalCount);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

型定義をオプショナルに更新し、if (!bucket) continue ガードの必要性を型レベルで保証すべきです。

実行時には commitContributionsByRepository 等が undefined になり得ます(テスト436-459行目で検証済み)が、型定義(75-77行目)では非オプショナル配列 ContributionsByRepoNode[] として宣言されています。TypeScriptは bucketsContributionsByRepoNode[][] と推論するため、if (!bucket) continue が不要に見えてしまい、将来の誤削除リスクがあります。

🔧 型定義の修正案(75-77行目)
-            commitContributionsByRepository: ContributionsByRepoNode[];
-            pullRequestContributionsByRepository: ContributionsByRepoNode[];
-            issueContributionsByRepository: ContributionsByRepoNode[];
+            commitContributionsByRepository?: ContributionsByRepoNode[];
+            pullRequestContributionsByRepository?: ContributionsByRepoNode[];
+            issueContributionsByRepository?: ContributionsByRepoNode[];
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/githubYearInReview.ts` around lines 122 - 133, Update the type
definitions for commitContributionsByRepository,
pullRequestContributionsByRepository, and issueContributionsByRepository to
allow undefined values, matching their runtime behavior. Ensure the buckets
collection and loop in the contribution aggregation flow retain the if (!bucket)
continue guard as type-required handling.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant