C++ Vector at/[] operator speed

后端 未结 9 1684
借酒劲吻你
借酒劲吻你 2021-01-02 16:19

In order to give functions the option to modify the vector I can\'t do

curr = myvec.at( i );
doThis( curr );
doThat( curr );
doStuffWith( curr );
         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 17:03

    From my own tests with similar code (compiled under gcc and Linux), operator[] can be noticeably faster than at, not because of the bounds checking, but because of the overhead of exception handling. Replacing at (which throws an exception on out-of-bounds) with my own bounds checking that raised an assert on out-of-bounds gave a measurable improvement.

    Using a reference, as Kristo said, lets you only incur the bounds checking overhead once.

    Ignoring bounds checking and exception handling overhead, both operator[] and at should be optimized to equivalent to direct array access or direct access via pointer.

    As Chris Becke said, though, there's no substitute for profiling.

提交回复
热议问题