Reputation: 1066
I have a function
that has a nested for loop
. As the function
iterates over more data, it is starting to slow down. How can I best optimize this function so that it runs a bit faster?
function rubicoGVB(arr, range) {
var res = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if ((arr[i] + arr[j]) / range < 16487665) {
res.push(arr[i]);
}
}
}
return res.length;
}
Upvotes: 0
Views: 63
Reputation: 1075705
(The biggest improvement you could make is described by Fast Snail in this comment: You don't need the res
array just to return its length; simply use a counter. Below are other improvements you could make.)
Looking at those loops, there's very little you can do other than:
Caching the length of the array, and
Caching arr[i]
instead of looking it up repeated in the j
loop
...which are minimal (but real) improvements, see len
and entry
below:
function rubicoGVB(arr, range) {
var res = [];
var len = arr.length;
var entry;
for (var i = 0; i < len; i++) {
entry = arr[i];
for (var j = i + 1; j < len; j++) {
if ((entry + arr[j]) / range < 16487665) {
res.push(entry);
}
}
}
return res.length;
}
Upvotes: 2