perf(tools): optimize last-user message extraction#762
Open
aymuos15 wants to merge 2 commits intosupermemoryai:mainfrom
Open
perf(tools): optimize last-user message extraction#762aymuos15 wants to merge 2 commits intosupermemoryai:mainfrom
aymuos15 wants to merge 2 commits intosupermemoryai:mainfrom
Conversation
|
|
||
| export const findLastUserMessage = <T extends { role: string }>( | ||
| messages: T[], | ||
| ): T | undefined => messages.findLast((msg) => msg.role === "user") |
This comment was marked as outdated.
This comment was marked as outdated.
Sorry, something went wrong.
Contributor
Author
There was a problem hiding this comment.
Have addressed this now. Thanks!
The build target is es2020 but findLast is ES2023, causing runtime errors in Node.js < 18. A reverse for-loop preserves the same perf improvement. Based on sentry review
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
memory-client.ts:findLastUserMessage(),extractTextFromMessageContent(), andjoinTextParts()slice().reverse().find()withArray.findLast()— avoids O(n) allocation on every callBenchmark results
Environment: 12th Gen Intel i7-12800H, Bun 1.2.22, Linux x64
getLastUserMessage(string content)slice/reverse/find)findLast)extractQueryText(multipart content)slice/reverse+filter/map/join)findLast+extractText)Key takeaways
getLastUserMessageat 1001 messages — becausefindLastshort-circuits immediately while the old approach always allocates a full copy viaslice().reverse()findLastavoids the allocation overhead even when both approaches scan the full arrayBenchmark source code
Test plan
bun run testinpackages/tools) — 43 passed, 29 skipped; 2 pre-existing failures unrelated to this PR (missingSUPERMEMORY_API_KEYenv var, missing./claude-memorytest module)bun run check-types) — zero errors in source files