From e2dcd95407d5202019cecd2bb2827ee6a4a8f9f3 Mon Sep 17 00:00:00 2001 From: Aaron Gokaslan Date: Mon, 6 Jun 2022 22:33:28 -0400 Subject: [PATCH] chore: optimize dictionary access in strip_padding numpy (#3994) * emplace field descriptors * reserve sufficient capacity * remove std::move * properly iterate through dict * make handle casting more explicit * Revert to old dict api --- include/pybind11/numpy.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index 0c77a98dd..43784f8e9 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -641,10 +641,14 @@ private: pybind11::str name; object format; pybind11::int_ offset; + field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset) + : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {}; }; + auto field_dict = attr("fields").cast(); std::vector field_descriptors; + field_descriptors.reserve(field_dict.size()); - for (auto field : attr("fields").attr("items")()) { + for (auto field : field_dict.attr("items")()) { auto spec = field.cast(); auto name = spec[0].cast(); auto spec_fo = spec[1].cast(); @@ -653,8 +657,8 @@ private: if ((len(name) == 0u) && format.kind() == 'V') { continue; } - field_descriptors.push_back( - {(pybind11::str) name, format.strip_padding(format.itemsize()), offset}); + field_descriptors.emplace_back( + std::move(name), format.strip_padding(format.itemsize()), std::move(offset)); } std::sort(field_descriptors.begin(),