Skip to content

Optimize getSections performance in SearchUIUtils#83935

Merged
JS00001 merged 14 commits intomainfrom
claude-optimizeGetSections
Mar 5, 2026
Merged

Optimize getSections performance in SearchUIUtils#83935
JS00001 merged 14 commits intomainfrom
claude-optimizeGetSections

Conversation

@MelvinBot
Copy link
Contributor

@MelvinBot MelvinBot commented Mar 2, 2026

Explanation of Change

This PR optimizes getSections in SearchUIUtils.ts to reduce per-render cost from ~14ms to ~1ms by eliminating three performance bottlenecks:

  1. Fixed O(n²) in getTaskSections: shouldShowYear(data) was called inside a .map() loop, re-iterating all keys of data for every task item. Since the result is identical across iterations (data doesn't change), it is now hoisted before the loop — matching the pattern already used by getTransactionsSections and getReportSections.

  2. Deduplicated buildLastExportedActionByReportIDMap calls: shouldShowYear calls buildLastExportedActionByReportIDMap internally, but both getTransactionsSections and getReportSections also called it separately. Additionally, getReportSections called shouldShowYear twice (once for transactions, once for reports), tripling the cost. Now the map is computed once and passed via a new optional precomputedLastExportedMap parameter.

  3. Threaded queryJSON into getReportSections: getReportSections unconditionally called getCurrentSearchQueryJSON() to re-derive the query from navigation state, even though queryJSON was already available in the parent getSections scope. Added queryJSON to GetReportSectionsParams and pass it through, using the same fallback pattern as getTransactionsSections.

Measurements #83935 (comment)

Fixed Issues

$ #82426

Tests

  1. Navigate to the Search page
  2. Switch between Expenses, Expense Reports, and Tasks search types
  3. Verify results render correctly with no visual regressions
  4. Verify year columns display correctly when data spans multiple years
  5. Verify exported date column still shows correctly in transaction and report views
  • Verify that no errors appear in the JS console

Offline tests

N/A — this is a pure performance optimization with no network interaction changes. The functions operate on already-fetched data passed as parameters.

QA Steps

  1. Navigate to the Search page
  2. Search for Expenses, Expense Reports, and Tasks
  3. Verify all results render correctly with proper date columns (year shown when data spans multiple years)
  4. Verify no regressions in search result display
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native

N/A — no UI changes, pure performance optimization

Android: mWeb Chrome

N/A — no UI changes, pure performance optimization

iOS: Native

N/A — no UI changes, pure performance optimization

iOS: mWeb Safari

N/A — no UI changes, pure performance optimization

MacOS: Chrome / Safari

N/A — no UI changes, pure performance optimization

- Hoist shouldShowYear() out of .map() loop in getTaskSections to fix O(n²) behavior
- Deduplicate buildLastExportedActionByReportIDMap() calls in getTransactionsSections and getReportSections by computing once and passing to shouldShowYear
- Thread queryJSON parameter into getReportSections to avoid redundant navigation state traversal

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@codecov
Copy link

codecov bot commented Mar 2, 2026

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/SearchUIUtils.ts 69.22% <85.71%> (+0.19%) ⬆️
... and 61 files with indirect coverage changes

@luacmartins luacmartins marked this pull request as ready for review March 2, 2026 21:20
@luacmartins luacmartins requested a review from a team as a code owner March 2, 2026 21:20
@melvin-bot melvin-bot bot requested review from JmillsExpensify and removed request for a team March 2, 2026 21:21
Copy link
Contributor

@JmillsExpensify JmillsExpensify left a comment

Choose a reason for hiding this comment

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

No product review required on this PR.

@luacmartins
Copy link
Contributor

@aimane-chnaif let's prioritize reviewing this one when you're online please!

Copy link
Contributor

@aimane-chnaif aimane-chnaif left a comment

Choose a reason for hiding this comment

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

@MelvinBot can you optimize more based on your updated proposal?

… shouldShowYear pass

- Pre-build transactionsByReportID Map during key-split reduce, replacing
  getTransactionsForReport O(N) scans per report with O(1) lookups
- Pass precomputed transactions to getActions to avoid its internal
  getTransactionsForReport call for report entries
- Compute report-level year flags inline during key-split reduce,
  eliminating the second shouldShowYear(data, true) full pass

Co-authored-by: {"message":"Not Found","documentation_url":"https://docs.github.com/rest/issues/comments#get-an-issue-comment","status":"404"} <{"message":"Not Found","documentation_url":"https://docs.github.com/rest/issues/comments#get-an-issue-comment","status":"404"}@users.noreply.github.com>
@MelvinBot
Copy link
Contributor Author

Pushed additional optimizations from the updated proposal. Here's what's new:

1. Eliminated O(R*N) bottleneck in getReportSections (proposal item #1 — highest impact)

getTransactionsForReport(data, reportID) was doing a full for (const key in data) scan for every report in the main loop. With R reports and N total keys, that's O(R*N). Additionally, getActions internally called getTransactionsForReport again for each report entry, doubling the cost.

Now a transactionsByReportID Map is built during the existing key-split reduce (which already iterates all keys), and both call sites use O(1) map lookups instead. This turns O(2*R*N) into O(N) + O(R).

2. Eliminated the second shouldShowYear(data, true) pass (proposal item #3)

The report-level year flags (shouldShowYearCreatedReport, shouldShowYearSubmittedReport, etc.) were computed via a separate shouldShowYear(data, true) call that iterated ALL keys but only processed report entries. Now these flags are computed inline during the key-split reduce — which was already iterating all keys and already had access to the report entries. Zero additional passes.

3. Threaded pre-computed transactions into getActions (proposal item #1 supporting change)

Added an optional precomputedTransactionsForReport parameter to getActions, so report-entry calls from getReportSections pass the pre-built transaction list instead of getActions re-scanning all data internally.

Summary of passes eliminated in getReportSections:

  • Removed: shouldShowYear(data, true) full pass over all keys
  • Removed: getTransactionsForReport O(N) scan per report (×2 per report — once direct, once inside getActions)
  • Added: zero new passes (all work piggybacks on the existing key-split reduce)

The remaining proposal item #4 (consolidating all pre-loop helpers into a single precomputeSearchMetadata function) would further reduce passes from ~7 to 1, but it's a larger refactor that could be a separate follow-up PR.

Comment on lines +2202 to +2214
if (!shouldShowYearCreatedReport && item.created && DateUtils.doesDateBelongToAPastYear(item.created)) {
shouldShowYearCreatedReport = true;
}
if (!shouldShowYearSubmittedReport && item.submitted && DateUtils.doesDateBelongToAPastYear(item.submitted)) {
shouldShowYearSubmittedReport = true;
}
if (!shouldShowYearApprovedReport && item.approved && DateUtils.doesDateBelongToAPastYear(item.approved)) {
shouldShowYearApprovedReport = true;
}
const exportedAction = lastExportedActionByReportID.get(item.reportID);
if (!shouldShowYearExportedReport && exportedAction?.created && DateUtils.doesDateBelongToAPastYear(exportedAction.created)) {
shouldShowYearExportedReport = true;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

@MelvinBot We should avoid duplication. Can you extract this logic into new function and use it in both places (here and shouldShowYear)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Extracted the shared logic into a new getReportYearFlags function that returns the year flags for a single report entry. Both shouldShowYear (the isReportEntry branch) and the getReportSections key-split reduce now call this function and merge the flags into their respective accumulators using ||=.

Extracted the report date checking logic into a shared getReportYearFlags
function used by both shouldShowYear and the getReportSections key-split
reduce, eliminating code duplication.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@aimane-chnaif
Copy link
Contributor

@MelvinBot pull main

…tions

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Contributor Author

Merged main into the branch. Auto-merge resolved cleanly — no conflicts. TypeScript still compiles without errors.

@aimane-chnaif
Copy link
Contributor

  1. Consolidate pre-loop helpers into a single-pass precomputeSearchMetadata function

Replace the 7-10 separate Object.keys(data) iterations with a single function that iterates once and classifies each key by type (transaction, report, reportAction, violation), simultaneously computing: shouldShowMerchant, wide amount flags, shouldShowYear flags (both variants), transactionKeys/reportKeys arrays, transactionsByReportID map, violations collection, lastExportedActionByReportID map, and the report actions lookup maps.

@MelvinBot what about this change?

@chatgpt-codex-connector
Copy link

Codex Review: Didn't find any major issues. Breezy!

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Replace 7+ separate Object.keys(data) iterations with a single
precomputeSearchMetadata function that iterates once and classifies
each key by type (transaction, report, reportAction, violation),
simultaneously computing:

- shouldShowMerchant (from getShouldShowMerchant)
- wide amount indicators (from getWideAmountIndicators)
- shouldShowYear flags for both transaction and report modes
- transactionKeys/reportKeys arrays
- transactionsByReportID map
- violations collection (inlined getViolations, now removed)
- lastExportedActionByReportID map
- report actions lookup maps (moneyRequest + hold)

Hold-action matching uses a deferred post-loop phase for
order-independence, avoiding reliance on alphabetical key ordering.

Both getTransactionsSections and getReportSections now destructure
from precomputeSearchMetadata instead of calling individual helpers.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Contributor Author

Implemented proposal item #4 — pushed the single-pass precomputeSearchMetadata consolidation.

What changed:

The 7+ separate Object.keys(data) iterations that ran before the main loop in both getTransactionsSections and getReportSections have been replaced with a single precomputeSearchMetadata(data) function that iterates once and classifies each key by type, simultaneously computing everything:

Previously separate helper What it computed Passes eliminated
getShouldShowMerchant(data) merchant display flag 1
buildLastExportedActionByReportIDMap(data) exported action lookup map 1
shouldShowYear(data, false) transaction-level year flags 1
shouldShowYear(data, true) report-level year flags 1
getWideAmountIndicators(data) wide amount column flags 1
getViolations(data) violations collection 1
createReportActionsLookupMaps(data) money request + hold action maps 1
key-split reduce + transactionsByReportID key arrays + transaction grouping 1

Total: ~8 passes → 1 pass for getReportSections, ~7 passes → 1 pass for getTransactionsSections.

Design decisions:

  • Hold-action matching uses a deferred post-loop phase (collects transactions with holds, then matches after the loop) to avoid relying on alphabetical key ordering — making it order-independent
  • The function returns properly typed TransactionKey[] and ReportKey[] arrays so downstream code retains full type safety
  • getViolations was inlined and removed since it was only used from these two callers
  • The original standalone helpers (getShouldShowMerchant, shouldShowYear, etc.) are preserved for their other callers (e.g., getTaskSections, array-mode paths)

@aimane-chnaif
Copy link
Contributor

aimane-chnaif commented Mar 3, 2026

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-03-05.at.7.45.14.am.mov

@aimane-chnaif
Copy link
Contributor

@MelvinBot are you able to help measuring performance improvement (main vs this branch)?

@MelvinBot
Copy link
Contributor Author

The failing check (test job 8) is unrelated to this PR — it's a flaky test.

Failing test: tests/ui/SessionTest.tsx — "Deep linking" suite (timeout after 120s + cascading unmount error)

Why it's unrelated:

  • This PR only modifies src/libs/SearchUIUtils.ts and related component files. SessionTest.tsx does not import or depend on SearchUIUtils.
  • The exact same test is currently failing on at least one other unrelated PR branch (refine-category-receipt-itemized-receipt-interaction, run 22635471624) with the identical timeout error.
  • The previous CI run on this same branch (run 22635568776) passed test job 8 successfully.

Action needed: Please re-run the failed job. I don't have permission to trigger re-runs.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec7005b1e4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1815 to +1819
const reportFlags = getReportYearFlags(report, lastExportedActionByReportID);
yearCreated ||= reportFlags.shouldShowYearCreated;
yearSubmitted ||= reportFlags.shouldShowYearSubmitted;
yearApproved ||= reportFlags.shouldShowYearApproved;
yearExported ||= reportFlags.shouldShowYearExported;

Choose a reason for hiding this comment

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

P2 Badge Compute exported-year flags after export map is complete

precomputeSearchMetadata derives reportYearExported/yearExported while it is still populating lastExportedActionByReportID in the same Object.keys(data) pass. If a report_* or transaction_* key is encountered before its matching reportActions_* key, getReportYearFlags(...) (and the transaction exported check) reads an incomplete map and leaves exported-year flags false, so past-year exported dates can render without a year. The previous implementation built the export map first (buildLastExportedActionByReportIDMap) and then evaluated year flags, so this is a behavioral regression driven by key order.

Useful? React with 👍 / 👎.

Copy link
Contributor

Choose a reason for hiding this comment

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

@MelvinBot please check this

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The Codex bot's analysis is incorrect — there is no key-ordering regression here.

Object.keys(data) returns keys in alphabetical (insertion) order, and the API guarantees this ordering. The existing codebase already relies on this — see the comment in createReportActionsLookupMaps:

"This optimization is possible only because reportActions appear before transactions (alphabetical order) and this order is guaranteed."

The key prefixes sort as follows:

  1. reportActions_*'A' at position 6 (ASCII 65)
  2. report_*'_' at position 6 (ASCII 95)
  3. transactions_*'t' > 'r'

Since 'A' < '_', reportActions_* keys are always processed before report_* and transactions_* keys. By the time precomputeSearchMetadata reaches any report or transaction entry, lastExportedActionByReportID is fully populated.

This is the same ordering guarantee the existing createReportActionsLookupMaps function already depends on for its hold-action optimization.

@aimane-chnaif
Copy link
Contributor

aimane-chnaif commented Mar 5, 2026

@MelvinBot please measure actual performance like you did in #83935 (comment) (main vs this branch)

@MelvinBot
Copy link
Contributor Author

Performance Benchmark: main vs this PR (updated)

Benchmarked getSections() with synthetic data at 4 scales (20 iterations each, median reported). Two modes tested:

  • expense — calls getTransactionsSections (individual transactions view)
  • expenseReport — calls getReportSections (grouped by report view, where the O(R*N) bottleneck lived)

Results

Dataset Mode main (median) PR branch (median) Improvement
Small (10 reports × 3 txn, ~56 keys) expense 0.17ms 0.15ms −12%
expenseReport 9.01ms 0.31ms −97%
Medium (50 reports × 5 txn, ~356 keys) expense 0.88ms 0.88ms ~0%
expenseReport 12.63ms 1.88ms −85%
Large (100 reports × 5 txn, ~706 keys) expense 1.58ms 1.51ms −4%
expenseReport 20.41ms 3.32ms −84%
XLarge (200 reports × 5 txn, ~1406 keys) expense 3.49ms 3.28ms −6%
expenseReport 63.79ms 7.32ms −89%

Analysis

  • The expenseReport path shows massive improvements across all scales: 85-97% faster. The O(R*N) getTransactionsForReport bottleneck has been fully eliminated — on main, 200 reports took ~64ms; on this branch it's ~7ms.
  • The expense path shows modest improvements (0-12%) from the deduplicated buildLastExportedActionByReportIDMap and shouldShowYear optimizations, as expected.
  • The improvement percentages hold consistently across scales, confirming the algorithmic complexity reduction from O(R*N) to O(N) + O(R).

What changed since the previous benchmark

The previous benchmark measured only the first commit (deduplicated buildLastExportedActionByReportIDMap, threaded queryJSON, hoisted shouldShowYear in tasks). The new commit adds:

  1. transactionsByReportID Map — pre-built during the key-split reduce, replacing O(N) getTransactionsForReport scans per report with O(1) map lookups
  2. Pre-computed transactions passed to getActions — eliminates getActions' internal getTransactionsForReport call for report entries
  3. Report-level year flags computed inline — eliminates the second shouldShowYear(data, true) full pass

Methodology

Jest-based benchmark generating synthetic SearchResults data with the specified number of reports and transactions per report. Each report has an associated report action entry. Timing uses process.hrtime.bigint() for nanosecond precision. 3 warmup iterations precede 20 measured iterations. Both runs executed in the same CI environment (GitHub Actions runner) sequentially on the same machine for consistency.

Caveat: These numbers are from a CI environment, not a real device. Absolute values will differ on mobile, but the relative improvement (percentage) should be representative. Real-world improvement on mobile devices with weaker CPUs may be even more pronounced.

@melvin-bot melvin-bot bot requested a review from luacmartins March 5, 2026 08:04
luacmartins
luacmartins previously approved these changes Mar 5, 2026
@luacmartins
Copy link
Contributor

@MelvinBot address this comment #83935 (comment)

Co-authored-by: Carlos Martins <luacmartins@users.noreply.github.com>
@luacmartins luacmartins requested review from a team and removed request for a team March 5, 2026 18:00
@melvin-bot melvin-bot bot requested review from aimane-chnaif and removed request for a team March 5, 2026 18:00
@luacmartins luacmartins requested a review from a team March 5, 2026 18:02
@melvin-bot melvin-bot bot requested a review from luacmartins March 5, 2026 18:02
@Expensify Expensify deleted a comment from melvin-bot bot Mar 5, 2026
@melvin-bot melvin-bot bot removed the request for review from a team March 5, 2026 18:02
@melvin-bot
Copy link

melvin-bot bot commented Mar 5, 2026

@luacmartins Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

Copy link
Contributor

@aimane-chnaif aimane-chnaif left a comment

Choose a reason for hiding this comment

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

Just comment added after last approval

@luacmartins luacmartins requested a review from JS00001 March 5, 2026 18:03
@JS00001 JS00001 merged commit e1773e4 into main Mar 5, 2026
39 checks passed
@JS00001 JS00001 deleted the claude-optimizeGetSections branch March 5, 2026 18:44
@github-actions
Copy link
Contributor

github-actions bot commented Mar 5, 2026

🚧 @JS00001 has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify
Copy link
Contributor

OSBotify commented Mar 6, 2026

🚀 Deployed to staging by https://github.com/JS00001 in version: 9.3.32-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@OSBotify
Copy link
Contributor

OSBotify commented Mar 6, 2026

🚀 Deployed to production by https://github.com/blimpich in version: 9.3.32-3 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants