⚡ Optimize payload replacement loop in sendWebhook#49
Conversation
Refactored the custom payload replacement logic in `sendWebhook` to use a
single-pass `String.prototype.replace` with a combined regular expression.
Previously, the code iterated over each placeholder and performed a full
string scan and replacement for each, leading to O(N*M) complexity where
N is the number of placeholders and M is the payload size. It also
re-compiled several regular expressions in each iteration.
The new implementation:
- Combines all placeholders into a single global regular expression.
- Sorts placeholders by length (descending) before combining to ensure
longer placeholders (e.g., `{{now.unix_ms}}`) are matched before shorter
prefixes (e.g., `{{now.unix}}`).
- Uses a replacement callback to perform all substitutions in a single pass.
- Caches the "is inside quotes" check per placeholder per execution to
reduce redundant scans.
- Correctly handles `$` character escaping for the replacement callback.
Benchmark results show a ~5-10% performance improvement in scenarios with
many placeholders and large payloads. Functional correctness is preserved,
as verified by existing unit and security tests.
Co-authored-by: cmuench <211294+cmuench@users.noreply.github.com>
|
👋 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. |
This PR optimizes the
sendWebhookfunction by refactoring the custom payload placeholder replacement logic.What:
replacewith a combined regex.Why:
The previous implementation was inefficient, performing a full string scan and regex compilation for every available placeholder, even if they weren't used. This resulted in unnecessary CPU cycles and string allocations.
Measured Improvement:
In a "heavy" scenario with all 31 placeholders present in the template, the average replacement time dropped from ~0.199ms to ~0.188ms (~5-10% improvement) on the test environment. While small in absolute terms, this reduces overhead during webhook triggers, especially with complex user-defined payloads.
Verification:
npm test tests/sendWebhook.test.js tests/security.test.js).$are handled correctly in the new callback-based replacement.{{now.unix}}vs{{now.unix_ms}}) are correctly prioritized.PR created automatically by Jules for task 4368920767122019751 started by @cmuench