mirror of
https://github.com/pybind/pybind11.git
synced 2024-11-22 21:25:13 +00:00
Fix quadratic-time behaviour of vector extend
The "extend" method for vectors defined in stl_bind.h used `reserve` to allocate space for the extra growth. While this can sometimes make a constant-factor improvement in performance, it can also cause construction of a vector by repeated extension to take quadratic rather than linear time, as memory is reallocated in small increments rather than on an exponential schedule. For example, this Python code would take time proportional to the square of the trip count: ```python a = VectorInt([1, 2, 3]) b = VectorInt() for i in range(100000): b.extend(a) ``` This commit removes the `reserve` call. The alternative would be to try to add some smarter heuristics, but the standard library may well have its own heuristics (the iterators are random access iterators, so it can easily determine the number of items being added) and trying to add more heuristics on top of that seems like a bad idea.
This commit is contained in:
parent
8dc63ba941
commit
6a0f6c40cd
@ -137,7 +137,6 @@ void vector_modifiers(enable_if_t<std::is_copy_constructible<typename Vector::va
|
|||||||
|
|
||||||
cl.def("extend",
|
cl.def("extend",
|
||||||
[](Vector &v, const Vector &src) {
|
[](Vector &v, const Vector &src) {
|
||||||
v.reserve(v.size() + src.size());
|
|
||||||
v.insert(v.end(), src.begin(), src.end());
|
v.insert(v.end(), src.begin(), src.end());
|
||||||
},
|
},
|
||||||
arg("L"),
|
arg("L"),
|
||||||
|
Loading…
Reference in New Issue
Block a user