-
Type:
Task
-
Resolution: Unresolved
-
Priority:
Major - P3
-
None
-
Affects Version/s: None
-
Component/s: BSON, Performance
-
None
-
None
-
Python Drivers
-
None
-
None
-
None
-
None
-
None
-
None
Summary:
Improve BSON encode dispatch with exact-type fast path
Description:
Context
The BSON encoder dispatches each value by type through a chain of subclass checks. For a value that is an exact built-in type, the chain still evaluates the subclass check (Py_IS_TYPE(value, T) || PyXxx_Check(value)). For non-matching types that walks the MRO or calls PyType_GetFlags, which a str value pays once per mismatch (Bool/Long/Float/Dict/List/Tuple/Bytes). Caching Py_TYPE(value) once and comparing against the built-in types by pointer avoids that work for every exact type.
Definition of done
- In _write_element_to_buffer, cache vtype = Py_TYPE(value) and dispatch exact types by pointer compare (str, dict, bool, long, float, list, tuple, bytes, datetime, regex), keeping the subclass checks in a fallback that reuses the same handlers using goto.
- Subclasses (SON, Int64, user int/str/bytes/list/tuple/dict subclasses) still encode correctly.
- test_bson.py and test_bson_corpus.py pass.
Pitfalls
- Keep the common types (str, dict) first in the dispatch order.
- datetime was last in the chain and paid every mismatch; the pointer compare removes that.
- Ensure values with a registered custom encoder (the handle_fallback label / TypeRegistry fallback) still encode correctly.
- blocks
-
PYTHON-6109 Stable-ABI (abi3) wheels for Python 3.11+
-
- Needs Triage
-
- is blocked by
-
PYTHON-6096 Add BSON benchmarking regression test support
-
- Needs Triage
-