Skip to content

Commit e2dcd95

Browse files
authored
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
1 parent 918892b commit e2dcd95

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

include/pybind11/numpy.h

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -641,10 +641,14 @@ class dtype : public object {
641641
pybind11::str name;
642642
object format;
643643
pybind11::int_ offset;
644+
field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset)
645+
: name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {};
644646
};
647+
auto field_dict = attr("fields").cast<dict>();
645648
std::vector<field_descr> field_descriptors;
649+
field_descriptors.reserve(field_dict.size());
646650

647-
for (auto field : attr("fields").attr("items")()) {
651+
for (auto field : field_dict.attr("items")()) {
648652
auto spec = field.cast<tuple>();
649653
auto name = spec[0].cast<pybind11::str>();
650654
auto spec_fo = spec[1].cast<tuple>();
@@ -653,8 +657,8 @@ class dtype : public object {
653657
if ((len(name) == 0u) && format.kind() == 'V') {
654658
continue;
655659
}
656-
field_descriptors.push_back(
657-
{(pybind11::str) name, format.strip_padding(format.itemsize()), offset});
660+
field_descriptors.emplace_back(
661+
std::move(name), format.strip_padding(format.itemsize()), std::move(offset));
658662
}
659663

660664
std::sort(field_descriptors.begin(),

0 commit comments

Comments
 (0)