Skip to content

Commit 91541c1

Browse files
authored
PERF: Improve efficiency of BlockValuesRefs (#59598)
* Improve efficency of _libs.internal * Re-add python version of ._rebuild_blknos_and_blklocs
1 parent 1e742f1 commit 91541c1

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

pandas/_libs/internals.pyx

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from collections import defaultdict
2-
import weakref
32

43
cimport cython
54
from cpython.pyport cimport PY_SSIZE_T_MAX
65
from cpython.slice cimport PySlice_GetIndicesEx
6+
from cpython.weakref cimport PyWeakref_NewRef
77
from cython cimport Py_ssize_t
88

99
import numpy as np
@@ -746,7 +746,7 @@ cdef class BlockManager:
746746
# -------------------------------------------------------------------
747747
# Block Placement
748748

749-
def _rebuild_blknos_and_blklocs(self) -> None:
749+
cpdef _rebuild_blknos_and_blklocs(self):
750750
"""
751751
Update mgr._blknos / mgr._blklocs.
752752
"""
@@ -890,12 +890,12 @@ cdef class BlockValuesRefs:
890890

891891
def __cinit__(self, blk: Block | None = None) -> None:
892892
if blk is not None:
893-
self.referenced_blocks = [weakref.ref(blk)]
893+
self.referenced_blocks = [PyWeakref_NewRef(blk, None)]
894894
else:
895895
self.referenced_blocks = []
896896
self.clear_counter = 500 # set reasonably high
897897

898-
def _clear_dead_references(self, force=False) -> None:
898+
cdef _clear_dead_references(self, bint force=False):
899899
# Use exponential backoff to decide when we want to clear references
900900
# if force=False. Clearing for every insertion causes slowdowns if
901901
# all these objects stay alive, e.g. df.items() for wide DataFrames
@@ -910,7 +910,7 @@ cdef class BlockValuesRefs:
910910
elif nr_of_refs > self.clear_counter:
911911
self.clear_counter = max(self.clear_counter * 2, nr_of_refs)
912912

913-
def add_reference(self, blk: Block) -> None:
913+
cpdef add_reference(self, Block blk):
914914
"""Adds a new reference to our reference collection.
915915
916916
Parameters
@@ -919,7 +919,7 @@ cdef class BlockValuesRefs:
919919
The block that the new references should point to.
920920
"""
921921
self._clear_dead_references()
922-
self.referenced_blocks.append(weakref.ref(blk))
922+
self.referenced_blocks.append(PyWeakref_NewRef(blk, None))
923923

924924
def add_index_reference(self, index: object) -> None:
925925
"""Adds a new reference to our reference collection when creating an index.
@@ -930,7 +930,7 @@ cdef class BlockValuesRefs:
930930
The index that the new reference should point to.
931931
"""
932932
self._clear_dead_references()
933-
self.referenced_blocks.append(weakref.ref(index))
933+
self.referenced_blocks.append(PyWeakref_NewRef(index, None))
934934

935935
def has_reference(self) -> bool:
936936
"""Checks if block has foreign references.

0 commit comments

Comments
 (0)