Performance issue for vector::size() in a loop in C++

前端 未结 10 786
离开以前
离开以前 2020-11-29 04:37

In the following code:

std::vector var;
for (int i = 0; i < var.size(); i++);

Is the

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 04:58

    The size() member function is called each time, but it would be a really bad implementation that wouldn't inline it, and a strange one where it wouldn't be a simple access of a fixed datum or a subtraction of two pointers.
    Anyway, you shouldn't worry yourself with such trivialities until you have profiled your application and found out that this is a bottleneck.

    However, what you should pay attention to is:

    1. The correct type for a vector's index is std::vector::size_type.
    2. There are types (some iterators, for example) where i++ might be slower than ++i.

    Therefore, the loop should be:

    for(vector::size_type i=0; i

提交回复
热议问题