简体   繁体   English

有什么方法可以优化 function?

[英]Any way to optimize function?

so, I have this function here所以,我这里有这个 function

const [shopItems,setShopItems] = useState("");_
 useEffect(()=> {
    commerce.products.list().then((product) => {
      setShopItems(product)
    });
  }, [])

  
  function categorize(category) {
    let categoryarray = []
    if (shopItems!= "s") {
      shopItems.data.forEach((el)=> {
        for (let i =0; i < el.categories.length; i++) {
          if (el.categories[i].slug == category) categoryarray.push(el)
        }
      })

    }
    return categoryarray;
  }


the useEffect Hook was just for context, I'm mostly concerned about the categorize function. useEffect Hook 仅用于上下文,我最关心的是分类 function。 Is there anyway to optimize this since I have observed that my website scrolls very slowly, and I think this might be one of the culprits behind the slow scrolling speeds.无论如何要优化这一点,因为我观察到我的网站滚动非常缓慢,我认为这可能是滚动速度慢的罪魁祸首之一。 Thanks in Advance!提前致谢!

The only way I can see to optimise that code is to exit as soon as a match is found.我能看到优化该代码的唯一方法是在找到匹配项后立即退出。 (I prefer using a while loop for this purpose). (我更喜欢为此目的使用while循环)。

shopItems.data.forEach(el => {
    let idx = 0;
    while (idx < el.categories.length) {
        if (el.categories[idx].slug == category) {
            categoryarray.push(el);
            break;
        } else {
            idx++;
        }
    }
});

If you wanted something that looked slightly better (not mixing forEach and for , for example) you could use this: (no performance enhancements as far as I can see though)如果您想要看起来稍微好一点的东西(例如,不要混合forEachfor ),您可以使用它:(据我所知,没有性能增强)

shopItems.data.forEach(el => {
    if (el.categories.map(({ slug }) => slug).includes(category)) categoryarray.push(el);
});

Or even use reduce :甚至使用reduce

let categoryarray = shopItems.data.reduce((a, c) => {
    if (c.categories.map(({ slug }) => slug).includes(category) return a.concat(c);
    else return a;
}, []);

The first option is still the most performant as realistically it will run through the loop less times.第一个选项仍然是性能最高的,因为实际上它将通过循环更少的时间。

You can use useMemo https://reactjs.org/docs/hooks-reference.html#usememo您可以使用 useMemo https://reactjs.org/docs/hooks-reference.html#usememo

useMemo works by having 2 parameters. useMemo 通过具有 2 个参数来工作。 A function and an array of dependencies, if any of the dependencies change it re-runs the provided function and stores the value, next render if the dependencies havent changed it just uses the previous value.一个 function 和一个依赖关系数组,如果任何依赖关系发生变化,它会重新运行提供的 function 并存储该值,如果依赖关系没有改变,则下一次渲染它只使用以前的值。

const categories = useMemo(() =>  
    let categoryarray = []
    if (shopItems!= "s") {
      shopItems.data.forEach((el)=> {
        for (let i =0; i < el.categories.length; i++) {
          if (el.categories[i].slug == category) categoryarray.push(el)
        }
      })

    }
    return categoryarray;
}, [shopItems.data, category])

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

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