Skip to content

perf(bridge): optimize slice and map reflection bindings#166

Open
repyh wants to merge 2 commits into
mainfrom
optimize-slice-and-map-binding-8095066981084513861
Open

perf(bridge): optimize slice and map reflection bindings#166
repyh wants to merge 2 commits into
mainfrom
optimize-slice-and-map-binding-8095066981084513861

Conversation

@repyh
Copy link
Copy Markdown
Owner

@repyh repyh commented May 27, 2026

Optimization audit implementation targeting unnecessary allocations and interface boxing in bridge/core/reflection.go.


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

Summary by CodeRabbit

  • Refactor

    • Faster, lower-overhead handling when transferring byte arrays and slices for improved runtime performance
    • More efficient map iteration and key formatting to reduce memory use
  • Bug Fixes

    • Reduced build/run errors related to unnecessary generated imports
  • Chores

    • Example dependency updated to an explicit v1.10.0 version for reproducible builds

Review Change Stack

- optimize `bindSlice` with a fast path for `[]byte` and `[N]byte` to map directly to JS `Uint8Array`, drastically reducing generic interface slice conversion overhead. Added `bufCopy` check for safe memory boundaries.
- optimize `bindMap` by replacing `v.MapKeys()` slice allocation with `v.MapRange()` iteration, and mapping numeric primitives directly to strings using `strconv` instead of `fmt.Sprint()` to avoid interface boxing.
- benchmarks showed `bindSlice` for 1MB `[]byte` dropping from ~66.8M ns/op to ~971K ns/op, and `bindMap` for `int` dropping from ~717K ns/op to ~632K ns/op.

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 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fefdf1c9-6c2f-437c-bf51-fc2cd769a2df

📥 Commits

Reviewing files that changed from the base of the PR and between c7cf9a3 and 95f0918.

⛔ Files ignored due to path filters (1)
  • examples/projects/link-shortener/typego.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • examples/projects/link-shortener/service_bin
  • examples/projects/link-shortener/typego.modules.json
  • internal/ecosystem/installer/install.go
  • patch2.diff
  • patch_build.diff
  • patch_dependencies.diff
  • patch_installer.diff
  • pkg/cli/cmd/build.go
  • pkg/cli/cmd/run.go
  • typego
✅ Files skipped from review due to trivial changes (1)
  • examples/projects/link-shortener/typego.modules.json

📝 Walkthrough

Walkthrough

This PR adds a byte-slice fast path in Go→JS binding (ArrayBuffer → Uint8Array fallback), improves bindMap iteration and numeric key formatting using strconv, and updates import-generation/installer logic to dedupe and gate external imports plus pins gin in an example.

Changes

Binding Layer Optimization

Layer / File(s) Summary
Add strconv import for numeric key formatting
bridge/core/patch.diff, bridge/core/patch_imports.diff, bridge/core/reflection.go, temp_patch.txt
Added strconv to imports to support efficient integer-to-string conversion for map keys.
Implement bindSlice byte-slice fast path with ArrayBuffer and Uint8Array
bridge/core/patch.diff, bridge/core/reflection.go, temp_patch.txt
bindSlice fast-paths []byte/[N]byte by copying bytes into an ArrayBuffer and attempting to construct a JS Uint8Array, with a fallback to returning the raw ArrayBuffer. Generic slice handling (preallocated values + NewArray) remains for other element types.
Optimize bindMap with MapRange iteration and strconv key formatting
bridge/core/patch.diff, bridge/core/reflection.go, temp_patch.txt
bindMap now iterates with MapRange() to avoid allocating MapKeys(), and converts map keys by kind: string via .String(), signed ints via strconv.FormatInt, unsigned/uintptr via strconv.FormatUint, else fmt.Sprint; values still bound via bindValue and set on the created JS object.

Import generation, installer, and dependency fixes

Layer / File(s) Summary
Deduplicate imports and gate external modules
patch2.diff, patch_build.diff, pkg/cli/cmd/build.go, pkg/cli/cmd/run.go
Import-block generation now tracks emitted modules to dedupe imports and skips external imports (module path contains .) unless registered in virtualModules from inspection; retains hard-skips for internal bridge-handled modules.
Installer/shim inspection failure guard
patch_installer.diff, internal/ecosystem/installer/install.go
When shim inspection fails, namedImports is not populated and the failure path is documented to avoid generating unused imports; warning messages remain.
Pin gin dependency in example modules
examples/projects/link-shortener/typego.modules.json, patch_dependencies.diff
github.com/gin-gonic/gin is pinned to v1.10.0 when no explicit version is present; example module file updated accordingly.

Sequence Diagram

sequenceDiagram
  participant Caller as Binding Caller
  participant bindSlice
  participant Uint8Array as JS Uint8Array
  participant bindMap
  participant strconv as strconv
  participant JSObj as JS Object

  Caller->>bindSlice: byte slice value
  bindSlice->>bindSlice: copy bytes to ArrayBuffer
  bindSlice->>Uint8Array: vm.Get("Uint8Array")
  alt Uint8Array available
    bindSlice->>Uint8Array: vm.New(...ArrayBuffer)
    alt Success
      Uint8Array-->>bindSlice: Uint8Array instance
    else Failure
      bindSlice-->>Caller: fallback to ArrayBuffer
    end
  else Unavailable
    bindSlice-->>Caller: return ArrayBuffer
  end

  Caller->>bindMap: map[K]V
  bindMap->>bindMap: MapRange() iterator
  loop per map entry
    bindMap->>bindMap: inspect key kind
    alt key is signed int
      bindMap->>strconv: FormatInt(key)
    else key is unsigned/uintptr
      bindMap->>strconv: FormatUint(key)
    else key is string
      bindMap->>bindMap: key.String()
    else
      bindMap->>bindMap: fmt.Sprint(key.Interface())
    end
    bindMap->>JSObj: set formattedKey:boundValue
  end
  bindMap-->>Caller: JS object
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I copied bytes with nimble paws,
ArrayBuffer hummed without a pause;
If Uint8Array won't play along,
I'll hand back the buffer — still not wrong.
MapRange hops, strconv sings the key's song!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: optimizing slice and map reflection bindings in the bridge module to reduce allocations and improve performance.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 optimize-slice-and-map-binding-8095066981084513861

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.

…al modules

When `typego build` or `typego run` fails to inspect an external module (e.g. due to go version incompatibilities), it currently skips generating the virtual module but still adds the standard go import in the `main.go` file. This causes the Go compiler to throw an "imported and not used" error.

This patch updates `build.go`, `run.go`, and `install.go` to explicitly keep track of which modules were successfully inspected. Only successfully inspected modules are added to the final import block in the scaffolded Go shim, and we avoid inserting imports that are missing their corresponding JS virtual module.

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