Skip to content

⚡ perf: optimize device lookup using O(1) map#199

Open
ysdede wants to merge 1 commit intomasterfrom
feat/optimize-device-lookup-12305252719686096870
Open

⚡ perf: optimize device lookup using O(1) map#199
ysdede wants to merge 1 commit intomasterfrom
feat/optimize-device-lookup-12305252719686096870

Conversation

@ysdede
Copy link
Owner

@ysdede ysdede commented Mar 4, 2026

💡 What:
Replaced an O(N) array .find() in the frequently-called getSettingsSnapshot effect with an O(1) Map.get() lookup. This was achieved by introducing availableDevicesMap via createMemo in appStore.

🎯 Why:
The lookup was occurring in a reactive scope (createEffect inside src/App.tsx), meaning it recalculates frequently. Using an array traversal (.find) causes unnecessary CPU overhead. By caching the devices in a map when the devices list actually updates, we guarantee optimal O(1) execution during all reactive reads.

📊 Measured Improvement:
A quick benchmark using 1,000,000 iterations on 10 devices proved the performance gain:

  • Baseline (Array.find): 418.07 ms
  • Optimized (Map.get): 7.67 ms
  • Result: ~54x improvement over baseline.

PR created automatically by Jules for task 12305252719686096870 started by @ysdede

Summary by Sourcery

Optimize device selection lookup by introducing a memoized device map and update related wiring.

Enhancements:

  • Add a memoized map of available devices in the app store and expose it for consumers.
  • Use the memoized device map in settings snapshot generation to avoid repeated linear scans of the devices list.

Build:

  • Check in a new Bun lockfile for dependency locking.

Tests:

  • Add a standalone benchmark script to compare array-based and map-based device lookup performance.
- Added `availableDevicesMap` memo in `appStore` to pre-calculate a dictionary of devices keyed by deviceId. - Refactored `getSettingsSnapshot` in `App.tsx` to use `availableDevicesMap().get()` instead of `.find()` over the array. - Included `benchmark_lookup.ts` showing a 54x performance improvement (418ms -> 7ms over 1,000,000 iterations).
@google-labs-jules
Copy link
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.

@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Mar 4, 2026

Reviewer's Guide

Replaces an O(N) device lookup in getSettingsSnapshot with an O(1) Map-based lookup, by introducing a memoized deviceId→MediaDeviceInfo map in the app store and wiring consumers to use it; also adds a small standalone benchmark and updates dependencies lockfile.

Sequence diagram for optimized device lookup in getSettingsSnapshot

sequenceDiagram participant AppComponent participant AppStore participant AvailableDevicesMap participant MediaDeviceInfo AppComponent->>AppComponent: call getSettingsSnapshot() AppComponent->>AppStore: selectedDeviceId() AppStore-->>AppComponent: selectedDeviceId AppComponent->>AppStore: availableDevicesMap() AppStore-->>AppComponent: Map deviceId_to_MediaDeviceInfo AppComponent->>AvailableDevicesMap: get(selectedDeviceId) AvailableDevicesMap-->>AppComponent: MediaDeviceInfo selectedDevice AppComponent->>AppComponent: build settings snapshot using selectedDevice 
Loading

Class diagram for appStore and App lookup changes

classDiagram class AppStore { +createSignal availableDevices() MediaDeviceInfo[] +createSignal selectedDeviceId() string +createMemo availableDevicesMap() Map~string, MediaDeviceInfo~ } class AppComponent { +getSettingsSnapshot() SettingsSnapshot } class MediaDeviceInfo { +string deviceId +string kind +string label +string groupId } class SettingsSnapshot { +object general +object audio } AppComponent --> AppStore : uses AppStore "1" o-- "*" MediaDeviceInfo : availableDevices AppStore "1" o-- "*" MediaDeviceInfo : availableDevicesMap values SettingsSnapshot "1" o-- "0..1" MediaDeviceInfo : selectedDevice 
Loading

File-Level Changes

Change Details Files
Introduce memoized deviceId→device map in app store and expose it via the store API.
  • Add availableDevicesMap memo derived from availableDevices signal using createMemo
  • Populate the map by iterating current availableDevices and inserting entries keyed by deviceId
  • Return availableDevicesMap from createAppStore alongside existing readonly state signals
src/stores/appStore.ts
Switch settings snapshot device lookup from array find to Map.get.
  • Update getSettingsSnapshot to read selectedDeviceId from appStore as before
  • Replace availableDevices().find(...) with availableDevicesMap().get(selectedDeviceId) for O(1) lookup
src/App.tsx
Add a local benchmark script to compare Array.find vs Map.get for device lookup.
  • Create benchmark_lookup.ts with mock device data and perf_hooks-based timing
  • Implement benchmarkArrayFind and benchmarkMapGet across 1,000,000 iterations and log results to console
benchmark_lookup.ts
Check in bun.lock dependency lockfile.
  • Add bun.lock to the repository to lock dependency resolution (contents not shown in diff)
bun.lock

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2026

Warning

Rate limit exceeded

@ysdede has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f7c92056-1820-4807-9915-3343eb62016a

📥 Commits

Reviewing files that changed from the base of the PR and between be505c3 and 13d67d4.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • benchmark_lookup.ts
  • src/App.tsx
  • src/stores/appStore.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/optimize-device-lookup-12305252719686096870

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 and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances application performance by refactoring a critical device lookup mechanism. By transitioning from an inefficient linear search to a constant-time map lookup, the system avoids unnecessary CPU overhead in a reactive context, leading to a substantial speedup in device information retrieval. This change improves the responsiveness and efficiency of the application, particularly in scenarios involving frequent device access.

Highlights

  • Performance Optimization: Optimized device lookup from an O(N) Array.find() operation to an O(1) Map.get() lookup within the frequently called getSettingsSnapshot effect.
  • New Data Structure: Introduced availableDevicesMap using createMemo in appStore to efficiently cache MediaDeviceInfo objects for quick retrieval.
  • Measured Improvement: Achieved a ~54x performance improvement in device lookup, reducing execution time from 418.07 ms to 7.67 ms over 1,000,000 iterations on 10 devices.
  • Benchmark Added: A new benchmark script (benchmark_lookup.ts) was added to demonstrate and verify the performance gains of using Map.get() over Array.find().
Changelog
  • benchmark_lookup.ts
    • Added a new script to benchmark the performance difference between Array.find and Map.get for device lookup.
  • bun.lock
    • Updated the Bun lockfile to reflect changes in dependencies, likely due to the addition of the benchmark script or other minor package updates.
  • src/App.tsx
    • Updated the getSettingsSnapshot function to utilize the newly created availableDevicesMap for O(1) device lookup, replacing the previous O(N) Array.find.
  • src/stores/appStore.ts
    • Added a createMemo signal, availableDevicesMap, which transforms the availableDevices array into a Map for efficient device ID-based lookups.
    • Exposed the new availableDevicesMap in the return object of createAppStore to make it accessible to other components.
Activity
  • The pull request was created automatically by Jules for task 12305252719686096870, initiated by @ysdede.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • Consider not exposing a mutable Map directly from the store (e.g., return a read-only wrapper or helper accessor) to avoid accidental mutations of availableDevicesMap from consumers.
  • The benchmark_lookup.ts script lives at the repo root and is part of the TS tree; consider moving it under a scripts/ or benchmarks/ directory (and/or excluding it from the build) so it doesn’t accidentally affect the production bundle.
  • Adding bun.lock changes the repo’s package-manager state; double-check this aligns with the project’s dependency management strategy and that other lockfiles (npm/yarn/pnpm) are handled consistently.
Prompt for AI Agents
Please address the comments from this code review: ## Overall Comments - Consider not exposing a mutable `Map` directly from the store (e.g., return a read-only wrapper or helper accessor) to avoid accidental mutations of `availableDevicesMap` from consumers. - The `benchmark_lookup.ts` script lives at the repo root and is part of the TS tree; consider moving it under a `scripts/` or `benchmarks/` directory (and/or excluding it from the build) so it doesn’t accidentally affect the production bundle. - Adding `bun.lock` changes the repo’s package-manager state; double-check this aligns with the project’s dependency management strategy and that other lockfiles (npm/yarn/pnpm) are handled consistently.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Copy link

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

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 effectively optimizes the device lookup from O(N) to O(1) by introducing a memoized Map of available devices. The implementation in appStore.ts using createMemo is correct and ensures the map is only recomputed when the device list changes. The usage in App.tsx is also updated correctly. I've added one suggestion to make the map creation in appStore.ts more concise and idiomatic.

Comment on lines +82 to +88
const availableDevicesMap = createMemo(() => {
const map = new Map<string, MediaDeviceInfo>();
for (const device of availableDevices()) {
map.set(device.deviceId, device);
}
return map;
});

Choose a reason for hiding this comment

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

medium

For conciseness and to use a more functional approach, you can create the Map directly from the array using the Map constructor with an array of key-value pairs. This avoids the explicit loop and makes the derivation more declarative.

 const availableDevicesMap = createMemo(() => new Map(availableDevices().map((device) => [device.deviceId, device])) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant