Optimizing the number of loop iterations in JavaScript
In the following code, a programmer checks if
the array contains the number 3
:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let exists = false;
for (let elem of arr) {
if (elem === 3) {
exists = true;
}
}
console.log(exists);
What's wrong with his decision? It seems
that no extra operations are done in the
loop. The problem, however, is that after
it is determined that the number 3
is in the array, the loop still continues
to iterate until the end of the array.
It would be most irrational if the number
3
is found somewhere at the beginning
of the array, and the array itself is, say,
1000
elements long. You get a thousand
useless extra iterations of the loop! Not
optimal.
We optimize code by stopping the loop in time:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let exists = false;
for (let elem of arr) {
if (elem === 3) {
exists = true;
break;
}
}
console.log(exists);
The following code calculates how many
array elements must be added to make
the sum greater than 10
. Perform
optimization:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = 0;
let i = 1;
for (let elem of arr) {
sum += elem;
if (sum <= 10) {
i++;
}
}
console.log(i);
The following code outputs even numbers from a given range. Perform optimization:
for (let i = 0; i <= 100; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
The following code outputs numbers
divisible by 2
and 3
at the same time. Perform optimization:
for (let i = 0; i <= 100; i++) {
if (i % 2 === 0 && i % 3 === 0) {
console.log(i);
}
}
The following code searches for all
Fridays the 13
th in the current
year. Perform optimization:
for (let i = 0; i <= 11; i++) {
let curr = new Date;
let last = new Date(curr.getFullYear(), i + 1, 0).getDate();
for (let j = 1; j <= last; j++) {
let date = new Date(curr.getFullYear(), i, j);
if (date.getDate() === 13 && date.getDay() === 5) {
console.log(date);
}
}
}