(improvement) (python code path only): cache namedtuple class in named_tuple_factory to avoid …#740
Draft
mykaul wants to merge 1 commit intoscylladb:masterfrom
Draft
Conversation
9ea1ed1 to
8398d42
Compare
…repeated exec() calls Cache the Row namedtuple class keyed on tuple(colnames) so Python's namedtuple() (which internally calls exec()) is only invoked once per unique column schema. For prepared statements the column names never change, eliminating redundant class creation on every result set. Cache is a plain dict keyed on tuple(colnames) (raw column names before cleaning). Error handling paths (SyntaxError, Exception) preserved unchanged. Cache is naturally bounded by the number of distinct queries.
8398d42 to
9a76016
Compare
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.
Cache the Row namedtuple class keyed on tuple(colnames) so Python's namedtuple() (which internally calls exec()) is only invoked once per unique column schema. For prepared statements the column names never change, eliminating redundant class creation on every result set.
Motivation
named_tuple_factory is the default row_factory in the driver. Every call to namedtuple('Row', columns) internally calls exec() to generate a new class -- this is surprisingly expensive. For prepared statements executing the same query repeatedly, the column names never change, yet we pay the namedtuple() + exec() cost on every result set.
Benchmark results
Benchmarks compare the original code (Before) against the new cached implementation (After). All timings in us (microseconds).
10 columns, 1 row (isolates class creation overhead):
5 columns, 100 rows:
10 columns, 100 rows:
Design notes
Tests
All existing unit tests pass (46 passed).
Pre-review checklist
./docs/source/.Fixes:annotations to PR description.