最好在for循环中声明变量来访问对象的嵌套属性吗?

huangapple go评论79阅读模式
英文:

Is it better to declare variables to access nested properties of objects in for loops?

问题

根据性能来看,在循环中声明变量并存储嵌套属性,然后在循环中使用变量进行访问通常更有效率,而不是直接访问嵌套对象的属性,如requestBody[i].c.d.g。这是因为在每次访问属性时,直接访问会导致不必要的属性查找,而将属性存储在变量中可以减少查找次数,提高性能。

英文:
// for example I have an object like this
const requestBody = [
    {
        a: 1,
        b: 2,
        c: {
            d: {
                e: 3,
                f: 4,
                g: {
                       h: {
                           i: 5,
                           j: {
                              k: 6
                           }
                       }
                   }
            }
        }
    }
]
// in for loop
for (let i = 0; i < requestBody.length; i++) {
     const g = requestBody[i].c.d.g;
     // do something related to g
     const k = g.h.j;
     // do something related to k
}

So, What I want to know here is according performance, is it better to declare variables and store nested properties and then access by variables in loops? or is it better to access nested properties of objects directly like requestBody[i].c.d.g and do someting related to g?

答案1

得分: 1

你嵌套属性以访问变量元素的方式完全取决于您的实际用例。因为在JSON文件中,我们只是这样做,但这完全取决于您的需求和您的数据。您不能每次都嵌套,很多时候您必须进行优化以访问单个元素。

所以尽量以实际用例和真实数据来考虑这个问题,只有这样您才能找到答案。

否则,也完全没问题。但使用循环来访问元素可能不是正确的方式,逐个访问这些元素的最佳方式是通过序列化和反序列化。

这只是基于我的经验的思考,其他人可以提出他们的观点。

英文:

The way you nested properties to access variable elements, it's totally based on your real use case.

Because in JSON files, we are doing this only but it's totally based on your requirement and your data. You can't do nested every time, many times you have to optimize it to access a single element.

So try to think of this with a real use case and real data then only you can find out.

Otherwise, it's totally fine. But using a loop and accessing the elements it's not perhaps the right way, the best way to access these elements one by one is via serialize and deserialize.

That's just my thinking based on my experience, others can give their opinion.

huangapple
  • 本文由 发表于 2023年6月15日 13:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定