C++ Vector at/[] operator speed

后端 未结 9 1636
借酒劲吻你
借酒劲吻你 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:06

    When performance is an issue, there is no substitute for profiling. The optimization capabilities of compilers change from version to version, and tiny, insignificant alterations to source code can dramatically change the resulting performace.

    No one can answer this question but yourself: Create a test harness, and throw several algorithms at it and see what you get.

    ps. if performance really is an issue, well, i got a factor 10 speed increase out of a png decoder by removing the vectors and replacing them with raw arrays. Again, this was for Visual Studio 6. I am not claiming that a raw array substitution will give you a factor 10 improvement, but it is something to try.

    0 讨论(0)
  • 2021-01-02 17:17

    Options that I see, in roughly inverse order of preference:

    1. Store pointers in your container instead of the actual objects. This may be advisable anyway, if the objects are complex enough that copying them around is problematic.
    2. Use the indexing operator [] instead of at().
    3. Just call at() once, and save it into a reference (see Kristo's answer above).
    4. Forget about it until you actually have a problem with excessive runtime. If that happens, profile your code first to make sure the bottleneck is here, and only then worry about doing one of the above to speed things up.

    Honestly, what you should do is play with the four different approaches, and just use the one that produces the easiest to understand code. In most cases we are happy to sacrifice a few machine cycles for code that is easier for human beings to maintain.

    0 讨论(0)
  • 2021-01-02 17:20

    Vectors are the most suited for access speed. Access to a random element in a vector is of complexity O(1) compared with O(n) for general linked-lists and O(log n) for link-trees.

    However this question is mis-placed as the answer to your other question has lead you astray by not explaining how to fix your original problem by using a reference.

    0 讨论(0)
提交回复
热议问题