Skip to content

refactor(bridge/core): daily performance optimization audit#159

Open
repyh wants to merge 1 commit into
mainfrom
daily-optimization-bridge-core-16463292254535626834
Open

refactor(bridge/core): daily performance optimization audit#159
repyh wants to merge 1 commit into
mainfrom
daily-optimization-bridge-core-16463292254535626834

Conversation

@repyh
Copy link
Copy Markdown
Owner

@repyh repyh commented May 20, 2026

This pull request executes the daily performance and optimization audit for bridge/core and eventloop/eventloop.go.

Changes Made:

  1. Interface Boxing & Allocations (bridge/core/reflection.go):
    • Swapped v.MapKeys() to v.MapRange() in bindMap to avoid intermediate slice allocations.
    • Replaced fmt.Sprint(key.Interface()) with a switch checking numeric kinds and using strconv.FormatInt/Uint. This prevents boxing numbers into interface{}.
  2. []byte Fast Path (bridge/core/reflection.go & arraybuffer.go):
    • Implemented a fast path in bindSlice to securely handle []byte values. If addressable, v.Bytes() is used; otherwise, it falls back gracefully.
    • Introduced ToUint8Array to convert Go byte slices into JavaScript Uint8Array instances with safe fallbacks if the global doesn't exist.
    • Deeply copies the array prior to initializing Uint8Array to avert JavaScript from mutating the host memory block.
  3. Cache Locality (eventloop/eventloop.go):
    • Re-organized the EventLoop struct to couple the running and autoStop boolean properties directly beside their protecting mu Mutex, optimizing cache line efficiency.
  4. Panic Protection (eventloop/eventloop.go):
    • Integrated sync.Once in CreatePromise callbacks to reliably ensure el.wg.Done() is fired precisely once, forestalling sync.WaitGroup underflow panics if JavaScript invokes resolve/reject repetitively.

All features run flawlessly per existing unit, e2e, and integration tests. Evaluated through make test & go test -v ./....


PR created automatically by Jules for task 16463292254535626834 started by @repyh

Summary by CodeRabbit

  • Bug Fixes

    • Fixed potential race condition in promise resolution handling.
  • Performance Improvements

    • Optimized byte array conversions for better performance.
    • Improved map iteration efficiency.
    • Enhanced key type handling for maps with various key types.

Review Change Stack

- Optimized `bindMap` using `v.MapRange()` and `strconv` to reduce interface boxing and allocations.
- Optimized `bindSlice` with a fast path for `[]byte`, converting to `Uint8Array` safely using copied arrays.
- Introduced `ToUint8Array` in `arraybuffer.go` with safe fallback to `ArrayBuffer`.
- Improved cache locality in `EventLoop` struct by grouping `running` and `autoStop` with their `mu` sync.Mutex.
- Ensured thread safety in `CreatePromise` using `sync.Once` to protect `wg.Done()` from multiple invocations.
- Added appropriate `// @optimized` comments.

Co-authored-by: repyh <63894915+repyh@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.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

📝 Walkthrough

Walkthrough

This PR adds safe Go-to-JavaScript byte array conversion, optimizes map iteration and key formatting in the JS bridge reflection layer, and hardens promise settlement in the EventLoop to prevent duplicate callback executions and memory leaks.

Changes

JS bridge and EventLoop improvements

Layer / File(s) Summary
Uint8Array conversion helper and byte slice optimization
bridge/core/arraybuffer.go, bridge/core/reflection.go
ToUint8Array converts Go byte slices to JS Uint8Array with ArrayBuffer fallback. bindSlice detects []byte, copies the data, and uses the helper to prevent JS mutations of Go memory.
Map iteration and numeric key optimization
bridge/core/reflection.go
bindMap replaces MapKeys() iteration with MapRange() for efficiency and uses strconv for integer/unsigned numeric keys while preserving fmt.Sprint fallback.
EventLoop promise settlement idempotency
eventloop/eventloop.go
EventLoop field reordering improves cache locality. CreatePromise wraps resolve and reject callbacks with sync.Once to ensure JS-thread settlement and WaitGroup decrement occur only once regardless of callback repetition.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A rabbit hops through typed arrays bright,
Promise once-guards settle right,
Maps iterate with range so keen,
Cache-lined fields keep code clean,
Memory safe, no leaks in sight! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'refactor(bridge/core): daily performance optimization audit' is vague and generic; it uses non-specific terms like 'daily' and 'audit' that don't clearly convey the actual technical changes made. Revise the title to be more specific about the main changes, such as 'refactor(bridge/core): optimize map iteration and byte slice conversion' to better reflect the actual improvements in MapRange, strconv usage, and ToUint8Array implementation.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch daily-optimization-bridge-core-16463292254535626834

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
bridge/core/reflection.go (1)

381-389: ⚡ Quick win

This optimization is intentional and currently has no impact on the codebase.

The recent change from fmt.Sprint(key.Interface()) to strconv for numeric keys was an intentional performance optimization (commit 230d8d1). However, there are no named numeric types with String() methods in the codebase, so no existing serialization behavior has changed. The default case still uses fmt.Sprint(key.Interface()) as a fallback.

If named numeric types with custom String() methods are added in the future and used as map keys, they would lose their custom string output. The suggested fix is valid defensive programming but addresses a hypothetical rather than an actual problem. If this pattern becomes a concern, it could be addressed then.

🤖 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 `@bridge/core/reflection.go` around lines 381 - 389, The numeric key branches
(switch on key.Kind()) currently format numbers with
strconv.FormatInt/FormatUint which will bypass any custom String()
implementations on named numeric types; update the numeric cases in the switch
that handle reflect.Int*/reflect.Uint* to first detect if the key's type
implements fmt.Stringer (use reflect.TypeOf((*fmt.Stringer)(nil)).Elem() and
key.Type().Implements(...)) and if so set keyStr = fmt.Sprint(key.Interface()),
otherwise fall back to strconv.FormatInt(key.Int(), 10) or
strconv.FormatUint(key.Uint(), 10); keep the existing reflect.String case and
the default fmt.Sprint fallback.
🤖 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.

Nitpick comments:
In `@bridge/core/reflection.go`:
- Around line 381-389: The numeric key branches (switch on key.Kind()) currently
format numbers with strconv.FormatInt/FormatUint which will bypass any custom
String() implementations on named numeric types; update the numeric cases in the
switch that handle reflect.Int*/reflect.Uint* to first detect if the key's type
implements fmt.Stringer (use reflect.TypeOf((*fmt.Stringer)(nil)).Elem() and
key.Type().Implements(...)) and if so set keyStr = fmt.Sprint(key.Interface()),
otherwise fall back to strconv.FormatInt(key.Int(), 10) or
strconv.FormatUint(key.Uint(), 10); keep the existing reflect.String case and
the default fmt.Sprint fallback.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 44aad6c1-6a55-4553-ae9e-ba89d38f7ea4

📥 Commits

Reviewing files that changed from the base of the PR and between b85f440 and 230d8d1.

📒 Files selected for processing (3)
  • bridge/core/arraybuffer.go
  • bridge/core/reflection.go
  • eventloop/eventloop.go

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.

1 participant