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

前端 未结 10 825
离开以前
离开以前 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 05:06

    I think that if the compiler can conclusively deduce that the variable var is not modified inside the "loop body"

    for(int i=0; i< var.size();i++) { 
        // loop body
    }
    

    then the above may be transposed to something equivalent of

    const size_t var_size = var.size();
    for( int i = 0; i < var_size; i++ ) { 
        // loop body
    }
    

    However, I am not absolutely sure, so comments are welcome :)

    Also,

    • In most situations, the size() member function is inlined, so the issue does not warrant worrying

    • The concern is perhaps equally applicable to the end() which is always used for iterator based looping, i.e. it != container.end()

    • Please consider using size_t or vector::size_type for the type of i [See Steve Jessop's comment below.]

提交回复
热议问题