Question 50: why does the nesting order of for loops affect performance?

Time:2021-11-22

Core: put less cycles on the outer layer to reduce the operation times of inner variables

//Nesting mode I
function first() {
    let startTime = new Date().getTime();

    for (let i = 0; i < 100; i++) {
        for (let j = 0; j < 1000; j++) {
            for (let k = 0; k < 10000; k++) {}
        }
    }

    let endTime = new Date().getTime();

    return endTime - startTime + 'ms';
}

//Nesting mode 2
function second() {
    let startTime = new Date().getTime();

    for (let i = 0; i < 10000; i++) {
        for (let j = 0; j < 1000; j++) {
            for (let k = 0; k < 100; k++) {}
        }
    }

    let endTime = new Date().getTime();

    return endTime - startTime + 'ms';
}

console.log(first()); // 382ms
console.log(second()); // 501ms

Nesting mode I

  • I executes once, J executes 1000 times, and K executes 1000 * 10000 times
  • I executes 100 times and j executes 100 times_ 1000 times K will execute 100_ 1000 * 10000 times
  • Total times = I (100) + J (100000) + K (1000000000) = 1000100100 times

The number of execution in the circulation body is 1000100100

Nesting mode 2

  • I executes once, J executes 1000 times, and K executes 1000 * 100 times
  • I executes 10000 times and j executes 10000 times_ 1000 times K will execute 10000_ 1000 * 100 times
  • Total times = I (10000) + J (10000000) + K (100000000) = 110010000 times

The number of execution in the circulation body is 110010000 times

The content / inspiration of the article is drawn from the following content

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]