Skip to content

Commit 3ed6f14

Browse files
committed
Reuse the buffer key of the parent header in OutStream.write
1 parent 7940a09 commit 3ed6f14

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

‎ipykernel/iostream.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,7 @@ def __init__(
550550
self._io_loop = pub_thread.io_loop
551551
self._buffer_lock = threading.RLock()
552552
self._buffers = defaultdict(StringIO)
553+
self._buffer_keys: dict[int, tuple[dict[str, Any], frozenset[Any]]] = {}
553554
self.echo = None
554555
self._isatty = bool(isatty)
555556
self._should_watch = False
@@ -774,9 +775,13 @@ def write(self, string: str) -> int | None: # type:ignore[override]
774775
raise ValueError(msg)
775776

776777
is_child = not self._is_master_process()
778+
# frozenset(parent.items()) is slow, so keep the keys of the last few parents
779+
entry = self._buffer_keys.get(id(parent))
780+
if entry is None or entry[0] is not parent:
781+
entry = self._buffer_keys[id(parent)] = (parent, frozenset(parent.items()))
777782
# only touch the buffer in the IO thread to avoid races
778783
with self._buffer_lock:
779-
self._buffers[frozenset(parent.items())].write(string)
784+
self._buffers[entry[1]].write(string)
780785
if is_child:
781786
# mp.Pool cannot be trusted to flush promptly (or ever),
782787
# and this helps.
@@ -815,6 +820,8 @@ def _rotate_buffers(self):
815820
with self._buffer_lock:
816821
old_buffers = self._buffers
817822
self._buffers = defaultdict(StringIO)
823+
if len(self._buffer_keys) > 8:
824+
self._buffer_keys = {}
818825
return old_buffers
819826

820827
@property

0 commit comments

Comments
 (0)