简体   繁体   中英

How to best optimize a function with a nested for-loop

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;
}

(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:

  1. Caching the length of the array, and

  2. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM