jeudi 7 janvier 2021

Which one is more efficient - For loop VS if statement

would it be more efficient to search for something trough a small table loop (the table has 1 to 3 entries) or by checking a 2d table wicht an if statement (this table is much bigger and can have hundreds of entries).

Loop though table:

for (var i = 0; i < TableA.length; i++) {
    if (TableA[i] == x then) {
        // process ..
        break;
    }
}

if statement:

if (tableB[x][y] == true) {
    // process ..
}

My guess is that the option with the if statement is faster with the drawback of the memory needed for the bigger table.

Aucun commentaire:

Enregistrer un commentaire