⚡️ Speed up function messages_to_prompt_string
by 29%
#56
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.
📄 29% (0.29x) speedup for
messages_to_prompt_string
inguardrails/utils/docs_utils.py
⏱️ Runtime :
498 microseconds
→385 microseconds
(best of44
runs)📝 Explanation and details
The optimized code achieves a 29% speedup through two key performance improvements:
1. String concatenation optimization: The original code uses
messages_copy += content
which creates a new string object on each iteration - an O(n²) operation for large inputs. The optimized version collects strings in a list and uses"".join(content_list)
at the end, which is O(n) and much more efficient.2. Reduced isinstance() calls: Instead of calling
isinstance()
twice per message (once forPrompt
, once forInstructions
), the optimized version uses a single call with a pre-defined tuple_prompt_types = (Prompt, Instructions)
. This reduces function call overhead.3. Minimized attribute access: The optimized code assigns
msg["content"]
tocontent_obj
once per iteration, avoiding repeated dictionary lookups.The performance gains are most pronounced with large-scale inputs: test cases with 500-1000 messages show 33-40% speedups, while small inputs (1-3 messages) are slightly slower due to the setup overhead of creating the list and tuple. The optimization particularly shines when processing many messages, making it ideal for batch processing scenarios or applications handling extensive message histories.
All behavior is preserved - same outputs, same exception handling, and same type support for
Prompt
,Instructions
, and plain strings.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-messages_to_prompt_string-mh1qj8pl
and push.