opencv / opencv

Open Source Computer Vision Library
https://opencv.org
Apache License 2.0
79.13k stars 55.83k forks source link

Should Mat::Resize commit more than asked for to amortize the number of reallocs? #20024

Open EdenSegal opened 3 years ago

EdenSegal commented 3 years ago

My code uses Mat as a sort of generalized vector to store values I generate on the fly. In order to do that, I use Mat::Resize to write values into more rows. The documentation for Mat::Resize says it works as std::vector does, but in fact std::vector gives you a promise that the push complexity will be o(1) amortized. The code here: https://github.com/opencv/opencv/blob/68d15fc62edad980f1ffa15ee478438335f39cc3/modules/core/src/matrix.cpp#L1035 commits only the asked number of elements, so it's o(n) complexity. Should it be changed to commit 2*nelems (or any other constant > 1)? I implemented my solution, and it made my code 2-4x faster. I also understand that reserving more than needed can cause memory problems, so I wanted to raise the discussion before pushing a pull request.

alalek commented 3 years ago

Mat's .push_back() / .resize() implementations are not effective. So consider other containers for this task (like std::vector).

This functionality is rarely used in OpenCV, so it is going to be optimized.


IMHO, this should be dropped at all to avoid maintaining of "GOD" all-in-one class.