Apply nested loops to calculate sum of products
by krui027
JavaScript
function testLoops(outer, inner, label) {
console.time(label);
let sum = 0;
for (let i = 0; i < outer; i++) {
for (let j = 0; j < inner; j++) {
sum += i * j;
}
}
console.timeEnd(label);
return sum; // 防止引擎优化掉循环
}
const big = 1_000_000; // 大次数
const small = 100; // 小次数
// 情况A:大的次数在外层
testLoops(big, small, "大在外");
// 情况B:大的次数在内层
testLoops(small, big, "大在内");