当前位置:网站首页>RI Gai series: push of STD container_ Why is back slower than []

RI Gai series: push of STD container_ Why is back slower than []

2022-06-23 21:06:00 mariolu

Recently, in analyzing the flame diagram data of operators , Found more std::vector::push_back operation , I wonder if it can be optimized here .

A few facts must be known .vector The capacity of ( Memory ) Never less , Even call clear Method , Unless used swap Method .(C++11 Language provides shrink_to_fit Method repair .)STL vector Another thorny problem with is that there are many ways to build . It can be used new perhaps push_back.

So what's the difference ?

push_back Except to put the data push Into the container , Also, the container memory size Size for boundary check . If the container doesn't have space to store new elements , The container memory will also be expanded once . We all know that capacity expansion means that the container goes to the system to find a larger memory address , Then copy the elements . So it is often used here reserver To pre allocate memory , Avoid capacity expansion . And the operator operator[] Just do some address searching , Then fill the address with data . It doesn't look very safe .

And it's instant use reserver Reserved space ,push_back Additional condition checks will also be performed , And this kind of examination is operator[] There won't be . Besides , and push_back increase size value (reserve Just set up capacity), So it will be updated every time .

In short ,push_back Do more than do operator[]—— That's why it's slower ( More accurate ).

here stackoverflow Threads also discuss more extension points , One of the more interesting things is that compared with simple new After performing operator[], One extra time memset It will reduce the processing time later . This is related to the system memory page management mechanism .https://stackoverflow.com/questions/20168051/why-push-back-is-slower-than-operator-for-a-previously-allocated-vector

The code here has also been modified accordingly . Before knowing in advance the number of elements to insert , Do it in advance resize operation , And then use operator[]. Of course, it cannot be said that obvious system optimization can be achieved , But at least for this function , Some improvements have been made .

原网站

版权声明
本文为[mariolu]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112262241507711.html