diff --git a/.jules/bolt.md b/.jules/bolt.md index 52f429b..ae7739f 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -16,4 +16,7 @@ **Action:** Use `strings.NewReader(str)` directly instead of `bytes.NewReader([]byte(str))` to eliminate the allocation overhead. ## 2026-09-11 - Memoize Dynamic Library Load (`ctypes.CDLL`) **Learning:** Found that `ctypes.CDLL(None, use_errno=True)` within `pidfd_open` and `pidfd_send_signal` fallback paths in `_sgt-process-token.py` re-loaded the C library dynamically on every call, causing measurable per-call overhead, analogous to the learning about `libc_pidfd_function` from 2024-08-27. -**Action:** Substituted the redundant inline `ctypes.CDLL` loads with the memoized module-level `_LIBC_WITH_ERRNO` global to eliminate repeated linking overhead. \ No newline at end of file +**Action:** Substituted the redundant inline `ctypes.CDLL` loads with the memoized module-level `_LIBC_WITH_ERRNO` global to eliminate repeated linking overhead. +## 2024-10-25 - Avoid mime.ParseMediaType in hot paths +**Learning:** Using `mime.ParseMediaType` for exact or prefix header matching (e.g., checking for `text/event-stream`) causes unnecessary memory allocations and parsing overhead in Go hot paths. +**Action:** Use `strings.HasPrefix` (combined with `strings.ToLower` if case insensitivity is needed) instead to prevent these allocations and reduce CPU overhead. diff --git a/cmd/sergeant-mcp-client/proxy.go b/cmd/sergeant-mcp-client/proxy.go index 2fe4e65..c20cd29 100644 --- a/cmd/sergeant-mcp-client/proxy.go +++ b/cmd/sergeant-mcp-client/proxy.go @@ -5,7 +5,6 @@ import ( "bytes" "fmt" "io" - "mime" "net/http" "strings" "sync" @@ -175,10 +174,13 @@ func (p *proxy) writeResponse(resp *response) { return } - mediaType, _, _ := mime.ParseMediaType(resp.contentType) + // Optimization: Use strings.HasPrefix instead of mime.ParseMediaType to prevent + // unnecessary memory allocations and parsing overhead in this hot path. + // We use strings.ToLower to correctly handle case-insensitive header matching. + // Expected impact: Eliminates a memory allocation per proxy response. p.outMu.Lock() defer p.outMu.Unlock() - if mediaType == "text/event-stream" { + if strings.HasPrefix(strings.ToLower(resp.contentType), "text/event-stream") { for _, data := range parseSSEData(resp.body) { fmt.Fprintf(p.stdout, "%s\n", data) }