From 9eac892c3e5c599ea11ed086d5a26bafce51de73 Mon Sep 17 00:00:00 2001 From: ilan-gold Date: Thu, 22 May 2025 11:57:34 +0200 Subject: [PATCH 1/3] (feat): use `np.zeros` for buffer creation when possible --- src/zarr/core/buffer/cpu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/zarr/core/buffer/cpu.py b/src/zarr/core/buffer/cpu.py index 8464518818..b2ef205d1f 100644 --- a/src/zarr/core/buffer/cpu.py +++ b/src/zarr/core/buffer/cpu.py @@ -154,7 +154,7 @@ def create( order: Literal["C", "F"] = "C", fill_value: Any | None = None, ) -> Self: - if fill_value is None: + if fill_value is None or fill_value == 0: return cls(np.zeros(shape=tuple(shape), dtype=dtype, order=order)) else: return cls(np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order)) From 29508cf002c500dac532ebb4feb428c71030ad17 Mon Sep 17 00:00:00 2001 From: ilan-gold Date: Thu, 22 May 2025 12:24:38 +0200 Subject: [PATCH 2/3] (fix): add comment and check --- src/zarr/core/buffer/cpu.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/zarr/core/buffer/cpu.py b/src/zarr/core/buffer/cpu.py index b2ef205d1f..3022bafb6f 100644 --- a/src/zarr/core/buffer/cpu.py +++ b/src/zarr/core/buffer/cpu.py @@ -154,7 +154,8 @@ def create( order: Literal["C", "F"] = "C", fill_value: Any | None = None, ) -> Self: - if fill_value is None or fill_value == 0: + # np.zeros is much faster than np.full, and therefore using it when possible is better. + if fill_value is None or (isinstance(fill_value, int) and fill_value == 0): return cls(np.zeros(shape=tuple(shape), dtype=dtype, order=order)) else: return cls(np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order)) From b0f815ffdb0273ac0faade44ff861abcb1d6b24a Mon Sep 17 00:00:00 2001 From: ilan-gold Date: Thu, 22 May 2025 16:10:47 +0200 Subject: [PATCH 3/3] (chore): relnote --- changes/3082.feature.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/3082.feature.rst diff --git a/changes/3082.feature.rst b/changes/3082.feature.rst new file mode 100644 index 0000000000..e990d1f3a0 --- /dev/null +++ b/changes/3082.feature.rst @@ -0,0 +1 @@ +Use :py:func:`numpy.zeros` instead of :py:func:`np.full` for a performance speedup when creating a `zarr.core.buffer.NDBuffer` with `fill_value=0`. \ No newline at end of file