Is std :: vector :: size () slower than manually tracking size?

Does it transmit the std::vector::size()size of the vector every time it is called, or does it maintain a counter that changes only when the vector changes? For example, if I have a class with a member std::vector<double>, will there be any speed advantage for tracking its size in a separate counter?

+3
source share
5 answers

size() guaranteed to have constant temporal complexity, and in any reasonable implementation will work as fast as you possibly can.

+12
source
this->_Mylast - this->_myFirst 

. , . , , , - . , , , . . , , . .

, , STL size().

+3

, . :

iterator begin() {return start;}
iterator end() {return finish;}
size_type size() const { return size_type(end() - begin());}

iterator start;
iterator finish;

"start", "finish" -, size() . , , -.

+2

- std::vector::size()

MSVC this->_Mylast - this->_Myfirst - .

+1

, . , , , . , . .. :

// reset vector of size=3 to value 10

for( size_t i=0; i < myvec.size(); ++i )
{
   myvec[i] = 10.0;
}

 myvec[0] = myvec[1] = myvec[2] = 10.0;

3d- , ip- .. std::vector, () , . , , , , . , , , .

PS: Valgrind is your friend to tell you where to optimize first. Indeed, the size operator often appears as the main candidate; at least for some algorithms.

Good luck

+1
source

All Articles