⚡️ Speed up method AES.decrypt by 2,845%
#143
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.
📄 2,845% (28.45x) speedup for
AES.decryptinskyvern/forge/sdk/encrypt/aes.py⏱️ Runtime :
9.81 seconds→333 milliseconds(best of5runs)📝 Explanation and details
The optimization implements key derivation caching to eliminate redundant expensive cryptographic operations. The key change is adding a
_cached_keyattribute that stores the derived key after the first computation.What was optimized:
self._cached_key: bytes | None = Nonein__init___derive_key()to return the cached key if available, otherwise compute, cache, and return itWhy this provides a massive speedup:
The PBKDF2HMAC key derivation with 100,000 iterations is computationally expensive (~10ms per call based on profiler data). In the original code, this expensive operation ran on every
decrypt()call. The optimization reduces this to a one-time cost per AES instance.Performance impact:
_derive_key()time dropped from 9.97s to 0.415skdf.derive()operation now only runs 35 times instead of 843 times in the test workloadWhen this optimization shines:
The test results show this optimization is particularly effective for:
test_decrypt_concurrent_same_key,test_decrypt_many_concurrent) where the same AES instance decrypts multiple messagestest_AES_decrypt_throughput_*tests) with batched operationsThread safety note: The caching is safe since AES instances are typically not shared across threads, and the key derivation parameters (secret_key, salt, IV) are immutable after initialization.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AES.decrypt-mjaaxyedand push.