简体   繁体   English

如何提高嵌套 for 循环的性能

[英]how nested for loop can be improved performance wise

Here is my for loop, It runs over 2 enums, and send both of them to the server, get's a value, and calculate the value through another for loop.这是我的 for 循环,它运行了 2 个枚举,并将它们都发送到服务器,获取一个值,然后通过另一个 for 循环计算该值。 Pretty sure it can be improved.很确定它可以改进。 here is the code:这是代码:

  const paths = [];
  for await (let category of Object.values(CategoriesEnum)) {
    for await (let format of Object.values(FormatsEnum)) {
      const totalPosts = await getPagesCount(category, format);
      const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
      for (let page = 1; page <= totalPages; page++) {
        paths.push({ params: { category: category , format: format page: page } });
      }
    }
  }
return paths;

My main goal is to reduce the time, although i understand that the server will get the same amount of queries so the differences won't be huge.我的主要目标是减少时间,尽管我知道服务器将获得相同数量的查询,因此差异不会很大。 Thanks.谢谢。

You can use [Promise.all][1].您可以使用 [Promise.all][1]。

Here's the sample snippet.这是示例代码段。

let promises = [];
let paths = [];

Object.values(CategoriesEnum).forEach(category => {
    Object.values(FormatsEnum).forEach(format => {
        promises.push(getPagesCount(category, format))
    })
});

const totalPostCounts = await Promise.all(promises);



totalPostCounts.forEach(totalPosts => {
    const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
    for (let page = 1; page <= totalPages; page++) {
        paths.push({ params: { category: category, format: format, page: page } });
    }
});

return paths;




[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Another Approach using same Methods使用相同方法的另一种方法

let promises = [];
let paths = [];


/*
Gather Api calls
*/
Object.values(CategoriesEnum).forEach(category => {
    Object.values(FormatsEnum).forEach(format => {
        promises.push(getPath(category, format))
    })
});

// wait for the call
const pathsArray = await Promise.all(promises);

// flat the array
pathsArray.forEach(pathArray => {
    paths = paths.concat(pathArray)
});


async function getPath(category, format) {
    let paths = [];

    const totalPosts = await getPagesCount(category, format);
    const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
    for (let page = 1; page <= totalPages; page++) {
        paths.push({ params: { category: category, format: format, page: page } });
    }

    return paths;
}

For the beginning, I would split logic into 3 parts:一开始,我将逻辑分为 3 个部分:

  1. Prepare async calls准备异步调用
  2. Resolve async calls in parallel并行解决异步调用
  3. Apply my business logic应用我的业务逻辑
const pagesPromises = []
for  (let category of Object.values(CategoriesEnum)) {
  for  (let format of Object.values(FormatsEnum)) {
    pagesPromises.push(getPagesCount(category, format))
  }
}

const totalPostsResults = await Promise.all(pagesPromises)

const paths = [];
totalPostsResults.forEach(totalPosts => {
  const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
  for (let page = 1; page <= totalPages; page++) {
    paths.push({ params: { category: category , format: format page: page } });
  }
})

return paths;

As other answers suggest, you can use Promise.all() .正如其他答案所暗示的那样,您可以使用Promise.all() Without much refactoring you can write:无需太多重构,您就可以编写:

const getStaticPaths = async () => {
  const paths = [];
  const promises = []; // : Array<Promise<void>> in ts

  Object.values(CategoriesEnum).forEach((category) => {
    Object.values(FormatsEnum).forEach((format) => {
      promises.push(async () => {

        const totalPosts = await getPagesCount(category, format); // <-- confusing name though, I'd prefer `getPostsCount` instead
        const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
        for (const page = 1; page <= totalPages; ++page)
          paths.push({ params: { category: category, format: format, page: page } });

      });
    });
  });

  await Promise.all(promises);
  return { paths };
};

export { getStaticPaths };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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