Skip to content

[Due for payment 2026-04-16] [$250] Optimize EmojiTrie Build Performance #86759

Closed

Description

@roryabraham

Proposal: Optimize EmojiTrie Build Performance

Background

The app uses a custom prefix trie for emojis. This data-structure is used to enable fast autocomplete. The buildEmojisTrie is called on App startup, along with locale loading logic.

Problem

When a user opens the emoji picker for the first time, the trie build blocks the JS thread longer than necessary. There are 4 inefficiencies we found:

Recursive inserts with string copies: Trie.add recurses once per character and calls substring(1) at each level, allocating a new string on every step
Double trie traversal per keyword: Every keyword does a search to check if it exists, then a separate add or update — walking the same path twice
Suggestions array rebuilt on every collision: When two emojis share a keyword, the entire suggestions array is recreated via spread rather than appended to
Quadratic name-part allocation: getNameParts uses slice(index).join('_') for each suffix of the name, generating O(n²) intermediate arrays and strings

Solution

Iterative inserts: Rewrite Trie.add, search, and update to use index-based character access in a loop, eliminating all per-character string allocations
Single-pass getOrCreate: Add a method that walks to the end node once and returns {node, isNew}, replacing the search + add/update double traversal everywhere
Mutable suggestions: Initialize suggestions as a stable array and push/unshift into it directly. Since the normalized keyword node shares the same metadata object by reference, it stays in sync automatically — no extra update needed
Linear name-part generation: Replace the map+slice+join in getNameParts with a single indexOf loop that appends suffixes directly with no intermediate allocations

Results:

Web: 26ms - 16ms  (-38.4%)
iOS: 140ms - 95ms (-32.14%)

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~022039022812847691682
  • Upwork Job ID: 2039022812847691682
  • Last Price Increase: 2026-03-31
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    External
    Daily
    Bug
    on Mar 31, 2026
  2. added
    Help Wanted
    on Mar 31, 2026
  3. melvin-bot commented on Mar 31, 2026

    @melvin-bot

    Current assignee @shubham1206agra is eligible for the External assigner, not assigning anyone new.

  4. removed
    Help Wanted
    on Mar 31, 2026
  5. changed the title [-]Optimize EmojiTrie Build Performance[/-] [+][$250] Optimize EmojiTrie Build Performance[/+] on Mar 31, 2026
  6. melvin-bot commented on Mar 31, 2026

    @melvin-bot
  7. roryabraham commented on Mar 31, 2026

    @roryabraham
    ContributorAuthor

    @shubham1206agra is acting as contributor for this one. Help not needed for now

  8. self-assigned this
    on Mar 31, 2026
  9. MelvinBot commented on Mar 31, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    The buildEmojisTrie function and underlying Trie class have four compounding algorithmic inefficiencies that cause excessive memory allocation and CPU work during trie construction:

    1. O(N²) string allocations per word in all Trie methods. Trie.add() (src/libs/Trie/index.ts:21-36) recurses once per character and calls substring(1) at each level, creating N intermediate strings of decreasing length. The same pattern exists in search() and update() (lines 42-70) which use substring(1) in while loops. Additionally, add() redundantly calls toLowerCase() on every recursive frame (line 22), even though the string is already lowercased from the first call.

    2. Double trie traversal per keyword. In addKeywordsToTrie (src/libs/EmojiTrie.ts:26-49) and createTrie (lines 80-93), every keyword is first searched via trie.search(keyword), then separately added/updated via trie.add(keyword, ...) or trie.update(keyword, ...). Both operations walk the same character-by-character path, doubling the traversal cost. When accent-normalized forms differ from the original, this becomes up to 4 traversals per keyword.

    3. O(K²) suggestions array copies on keyword collisions. When multiple emojis share a keyword (src/libs/EmojiTrie.ts:37-43), the entire existing suggestions array is spread into a new array ([...(keywordNode.metaData.suggestions ?? []), suggestion]) instead of being mutated with push()/unshift(). For K emojis sharing a keyword, this copies O(K²) total elements.

    4. O(N²) intermediate allocations in getNameParts. The function (src/libs/EmojiTrie.ts:58-61) uses nameSplit.map((_, index) => nameSplit.slice(index).join('_')), which for each suffix creates a new array via slice() and a new string via join(), yielding quadratic work in the number of underscore-separated parts.

    What changes do you think we should make in order to solve the problem?

    1. Iterative index-based Trie methods: Rewrite add(), search(), and update() to use a character index variable in a loop (e.g., word.charCodeAt(i)) instead of substring(1). Call toLowerCase() once at the entry point only. This eliminates all per-character string allocations, reducing each operation from O(N²) to O(N) character work.

    2. Single-pass getOrCreate method: Add a new method to Trie that walks to the end node once and returns {node, isNew}. Replace the search + add/update double-traversal pattern in both addKeywordsToTrie and createTrie with this single-pass operation.

    3. Mutable suggestions arrays: Initialize suggestions as a stable array and use push()/unshift() directly. Since the trie node's metadata references the same array object, changes are reflected everywhere without needing to create new arrays or metadata objects.

    4. Linear getNameParts: Replace the map + slice + join pattern with a single indexOf('_') loop that uses string.substring(pos) to extract each suffix directly from the original string, avoiding all intermediate array allocations.

    What alternative solutions did you explore? (Optional)

    • Lazy trie construction (build only when emoji picker opens) — this shifts the cost but doesn't reduce it, and could cause UI jank on first open.
    • Pre-computed trie (build at compile time) — would eliminate runtime cost entirely, but adds build complexity and inflates bundle size with a serialized data structure.
    • Web Worker offloading — moves work off the main thread but doesn't reduce total CPU, and adds complexity for cross-thread communication.

    The proposed in-place algorithmic improvements are the simplest and most effective approach: they directly reduce the work done without architectural changes.


    Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

  10. rinej commented on Apr 3, 2026

    @rinej
    Contributor

    @elirangoshen draft PR #86313 touches the same area - it both defers the trie build to first use and replaces the Trie with a flat Map + sorted array with binary search

    There's overlap, but I think the safest path forward might be to combine the best parts of both:

    Defer the trie build to first use (from Eli's PR) - right now buildEmojisTrie is called eagerly in LocaleContextProvider on startup. Eli's PR introduces a lazy getEmojiSearchIndex() that only builds on the first actual emoji interaction. The same lazy init pattern can be applied to the existing Trie without replacing the data structure - should be a big win for startup with minimal risk

    Optimize the Trie internals (from this proposal) - iterative inserts, single-pass getOrCreate, mutable suggestions, and linear name-part generation are great, without changing the public API.

    Skip the full data structure replacement - swapping the Trie for a Map + binary search has the largest regression risk (new search semantics, new API for consumers in EmojiUtils.tsx, test changes across multiple files) and may not be worth the risk, the part 1 and ) together should address the performance concerns

    Curious what do you think?

  11. 23 remaining items

  12. jponikarchuk commented on Apr 9, 2026

    @jponikarchuk

    Deploy Blocker #87453 was identified to be related to the PR #87253 that attempted to fix this issue.

  13. added
    Daily
    and removed
    Weekly
    on Apr 15, 2026
  14. melvin-bot commented on Apr 16, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • (if NewFeature) I have created a PR for any necessary HelpDot updates, or I confirmed no updates are necessary.
    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2039022812847691682/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  15. roryabraham commented on Apr 16, 2026

    @roryabraham
    ContributorAuthor

    Reviewer: @shubham1206agra owed $250 via NewDot

    I ended up doing the reviewer checklist on this one, so I don't think any payments are due

  16. roryabraham commented on Apr 16, 2026

    @roryabraham
    ContributorAuthor

    No payments due

  17. roryabraham commented on Apr 16, 2026

    @roryabraham
    ContributorAuthor

    Sorry, I made a mistake. I think we had two separate pull requests for this same issue:

  18. mallenexpensify commented on Apr 17, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @shubham1206agra due $250 via NewDot
    Contributor+: @rojiphil due $250 via NewDot

  19. JmillsExpensify commented on May 1, 2026

    @JmillsExpensify
    Contributor

    $250 approved for @shubham1206agra

  20. quinthar commented on Jun 29, 2026

    @quinthar
    Contributor

    Approved $250 to @rojiphil

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

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions