How to Improve the Efficiency of For Loop--Innovation of Zhaoyi

1. Place the instantiated variable outside the loop:

#include <iostream>

int main() {
    // 实例化变量放在for循环外部
    int my_variable = 0;

    for (int i = 0; i < 5; i++) {
        my_variable += i;
        std::cout << my_variable << std::endl;
    }

    return 0;
}

2, i++ modification++i:

【013 Keyword】The difference between ++a and a++ 

The post-increment operator needs to copy the value of the original variable to a temporary storage space, and the value of the temporary variable will not be returned until the operation is completed . So the pre-increment operator is more efficient than the post-increment operator.

3. The loop condition uses < to be faster than <=, > to be faster than >=:

The reason why < is faster than <= and > is faster than >= in the loop condition is mainly due to the different computational complexity of the operators.

Specifically:

< and > are simple binary relational operators that only compare the magnitude relationship of two values.

<= and >= actually do the < or > judgment first, and then judge the = condition again.

4. The double-layer for loop operates on the array. The long loop has high efficiency in the inner layer, and the long loop has low efficiency in the outer layer:

The array adopts the row-first access principle, which is consistent with the storage order of elements.


Reference content: Multiple for loop optimization to improve operating efficiency_A large number of for loop calculation speed optimization_Shan Yu's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_41709234/article/details/132645897