[英]How to best optimize a function with a nested for-loop
I have a function
that has a nested for loop
. 我有一个嵌套的for loop
function
。 As the function
iterates over more data, it is starting to slow down. 随着function
迭代更多数据,它开始变慢。 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.) (Fast Snail 在此评论中描述了您可以做出的最大改进:您不需要res
数组来返回其长度;只需使用一个计数器即可。以下是您可以做出的其他改进。)
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 缓存arr[i]
而不是在j
循环中重复查找它
...which are minimal (but real) improvements, see len
and entry
below: ...这是最小(但实际)的改进,请参见下面的len
和entry
:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.