perf: optimize audio engine callback removal with Set#219
perf: optimize audio engine callback removal with Set#219
Conversation
Refactored callback arrays in `AudioEngine` to use `Set` for O(1) removals. This eliminates the O(N) `.filter()` garbage collection overhead during unsubscriptions, crucial for high-frequency observer management.
|
👋 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 New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Review Summary by QodoOptimize AudioEngine callback removal with Set data structure
WalkthroughsDescription• Replace callback arrays with Sets for O(1) removal performance • Eliminate O(N) filter operations during unsubscriptions • Refactor four callback collections: segmentCallbacks, windowCallbacks, audioChunkCallbacks, visualizationCallbacks • Measured 79% execution time reduction in benchmark tests Diagramflowchart LR
A["Array-based callbacks<br/>O(N) filter removal"] -->|"Refactor to Set"| B["Set-based callbacks<br/>O(1) delete removal"]
B -->|"Result"| C["79% faster<br/>unsubscriptions"]
File Changes1. src/lib/audio/AudioEngine.ts
|
Summary of ChangesHello, 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 the performance of the Highlights
Using Gemini Code AssistThe 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
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 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. Footnotes
|
Code Review by Qodo
1. Unsubscribe can skip callbacks
|
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- Switching from arrays to Sets changes semantics for duplicate registrations (the same callback can now only be registered once); if callers might rely on multiple registrations or reference equality of different wrapper functions, consider clarifying or guarding against that behavior change.
- Now that
windowCallbacks,segmentCallbacks, etc. are Sets, double-check all their read/iteration sites in this file for any use of array-specific APIs (e.g.,.length, index access,.filter,.map) and update them to iterate the Set instead to avoid runtime errors.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Switching from arrays to Sets changes semantics for duplicate registrations (the same callback can now only be registered once); if callers might rely on multiple registrations or reference equality of different wrapper functions, consider clarifying or guarding against that behavior change.
- Now that `windowCallbacks`, `segmentCallbacks`, etc. are Sets, double-check all their read/iteration sites in this file for any use of array-specific APIs (e.g., `.length`, index access, `.filter`, `.map`) and update them to iterate the Set instead to avoid runtime errors.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
There was a problem hiding this comment.
Code Review
This pull request effectively optimizes callback management by replacing arrays with Sets, which will improve performance during unsubscription by reducing it to an O(1) operation. The implementation is correct and consistently applied across all callback collections. I have one suggestion to improve code readability by extracting a complex inline type into a named interface.
| private windowCallbacks = new Set<{ | ||
| windowDuration: number; | ||
| overlapDuration: number; | ||
| triggerInterval: number; | ||
| callback: (audio: Float32Array, startTime: number) => void; | ||
| lastWindowEnd: number; // Frame offset of last window end | ||
| }> = []; | ||
| }>(); |
There was a problem hiding this comment.
For improved readability and maintainability, consider extracting the inline type for windowCallbacks into a named interface. This makes the code cleaner and the type reusable.
For example, you could define an interface at the top of the file or before the class:
interface WindowCallbackEntry {
windowDuration: number;
overlapDuration: number;
triggerInterval: number;
callback: (audio: Float32Array, startTime: number) => void;
lastWindowEnd: number;
}And then use it here:
private windowCallbacks = new Set<WindowCallbackEntry>();| onAudioChunk(callback: (chunk: Float32Array) => void): () => void { | ||
| this.audioChunkCallbacks.push(callback); | ||
| this.audioChunkCallbacks.add(callback); | ||
| return () => { | ||
| this.audioChunkCallbacks = this.audioChunkCallbacks.filter((cb) => cb !== callback); | ||
| this.audioChunkCallbacks.delete(callback); | ||
| }; |
There was a problem hiding this comment.
1. Unsubscribe can skip callbacks 🐞 Bug ✓ Correctness
During callback dispatch, unsubscribing now mutates the same Set being iterated, which can cause later callbacks in the same notify cycle to be skipped. Previously, unsubscription reassigned a new array (filter) so the in-flight iteration over the old array would continue unaffected.
Agent Prompt
### Issue description
Callback unsubscribe now uses `Set.delete()` which mutates the same collection being iterated during dispatch. This can skip callbacks later in the same notify cycle (behavioral regression vs the old array+reassignment approach).
### Issue Context
In `AudioEngine`, event dispatch iterates over Sets directly (audio chunks, window callbacks, segments, visualization). Unsubscribe closures delete from those Sets.
### Fix Focus Areas
- src/lib/audio/AudioEngine.ts[687-698]
- src/lib/audio/AudioEngine.ts[729-762]
- src/lib/audio/AudioEngine.ts[764-778]
- src/lib/audio/AudioEngine.ts[946-967]
### What to change
- Iterate over a snapshot for each dispatch loop, e.g. `for (const cb of Array.from(this.audioChunkCallbacks)) { ... }` and similarly for `windowCallbacks`, `segmentCallbacks`, and `visualizationCallbacks`.
- Keep the underlying storage as `Set` so removals stay O(1); only snapshot at dispatch time.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
💡 What: Refactored callback arrays in
AudioEngineto useSetfor O(1) removals.🎯 Why: To eliminate the O(N)
.filter()garbage collection overhead during unsubscriptions, keeping GC pauses low in the audio processing engine.📊 Measured Improvement:
Benchmark with 10k subscribe/unsubscribe cycles for 100 listeners:
PR created automatically by Jules for task 230949484791968314 started by @ysdede
Summary by Sourcery
Enhancements: