(improvement) Lazily initialize ResponseFuture._errors dict#801
Closed
mykaul wants to merge 1 commit into
Closed
Conversation
Change _errors initialization from {} to None, with a _add_error()
helper that creates the dict on first use. This saves one dict
allocation (~232 bytes on CPython) per successful query, which is the
overwhelmingly common case.
On the read side, the single consumer (NoHostAvailable) uses
'self._errors or {}' to handle the None case. The falsy check in
_send_request_on_next_host() works unchanged since None is falsy.
Author
Benchmark results (CPython 3.14, 500k iterations)Per-call timing:
Memory savings:
|
Author
|
I don't think it's safe for multi-threading. |
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
Change
ResponseFuture._errorsinitialization from{}toNone, with a_add_error()helper that creates the dict on first use. Saves one dict allocation per successful query.Motivation
The vast majority of queries succeed without errors. Pre-allocating an empty
{}for_errorson everyResponseFuturewastes memory. By deferring allocation to first error, successful queries (the common case) avoid this allocation entirely.Benchmark (CPython 3.14, per-call)
Timing:
Memory:
sys.getsizeof({})= 64B →sys.getsizeof(None)= 16B)The primary benefit is reduced GC pressure from eliminating a dict allocation on every successful query.
Changes
cassandra/cluster.py:__init__:self._errors = Noneinstead ofself._errors = {}_add_error(host, error)method that lazily creates the dictself._errors[host] = ...) converted toself._add_error(host, ...)self._errors or {}to handleNone(forNoHostAvailable)Testing
Unit tests pass (58/58 in test_response_future.py and test_cluster.py). Thread safety is preserved —
_add_error()runs under the GIL and individual dict assignment is atomic.