⚡️ Speed up method AES.encrypt by 3,144%
#142
Open
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.
📄 3,144% (31.44x) speedup for
AES.encryptinskyvern/forge/sdk/encrypt/aes.py⏱️ Runtime :
15.0 seconds→464 milliseconds(best of20runs)📝 Explanation and details
The optimized code achieves a 31x speedup (3144% improvement) and 4x throughput increase (300% improvement) through two key optimizations:
Primary Optimization: Key Derivation Caching
The most significant performance gain comes from caching the expensive PBKDF2 key derivation. In the original code,
_derive_key()performed 100,000 iterations of PBKDF2-HMAC-SHA256 on every single encryption call, consuming 99.9% of execution time (15.07 seconds).The optimized version adds:
This reduces key derivation from 1,273 expensive operations to just 39, since the derived key is identical for all encryptions using the same AES instance (same secret_key and salt).
Secondary Optimization: Padding Performance
The
_padmethod was optimized from:to:
This avoids creating an intermediate list object, reducing both memory allocation and execution time by ~27% for the padding operation.
Impact Analysis
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AES.encrypt-mjaa28jyand push.