Why is std::vector::operator[] 5 to 10 times faster than std::vector::at()?

前端 未结 3 1616
难免孤独
难免孤独 2020-12-02 09:05

During program optimization, trying to optimize a loop that iterates through a vector, I found the following fact: ::std::vector::at() is EXTREMELY slower than operator[] !<

3条回答
  •  星月不相逢
    2020-12-02 09:50

    You don't do anything with the return value, so if the compiler inlines these functions it can optimize them away completely. Or perhaps it can optimize away the subscript ([]) version completely. Running without optimizations is useless from a performance measurement perspective, what you need is some simple but useful program to exercise the functions so they don't just get optimized away. For example you could shuffle the vector (randomly swap 50000 pairs of elements).

提交回复
热议问题