3 ms·
for (let i = 0; i < a.length; i++) { a[i] = a[i]*2 } Has to be converted into something that can be run onto a machine that won't cause a fatal error if
by codefined 8y ago
for (let i = 0; i < a.length; i++) {
a[i] = a[i]*2
}
Has to be converted into something that can be run onto a machine that won't cause a fatal error if the array `a` doesn't have an item at index `i` (e.g. negative index). It can be converted to the following by a naive compiler:
for (let i = 0; i < a.length; i++) {
if (i > 0 && a < a.length) { // safe to access
a[i] = a[i] * 2
} else {
throw('in a safe way')
}
}
Or, to avoid repetitive checks to a.length:
const temp = a.length
for (let i = 0; i < temp; i++) {
if (i > 0 && a < temp) { // safe to access
a[i] = a[i] * 2
}
}
A more advanced compiler might realise that the if statement is irrelevant, we've defined it in the loop that we'll never have a negative `i` or one above the length of the array, so we can just avoid those checks entirely and actually revert back to the original code to compile. This is not always the case:
const temp = a.length
for (let i = 0; i < temp; i++) {
a[i] = a[i]*2
}
This comes up in interesting places, like why it is faster to go through an array backwards than forwards[0].
[0] https://stackoverflow.com/questions/8689573/why-is-iterating-through-an-array-backwards-faster-than-forwards https://stackoverflow.com/questions/8689573/why-is-iterating...