gpt4 book ai didi

javascript - 如果我们将对象的属性分配给另一个变量然后使用它,是否会影响代码的速度效率?

转载 作者:行者123 更新时间:2023-11-29 20:59:38 26 4
gpt4 key购买 nike

我想知道如果我每次都使用另一个变量来访问对象的属性或访问我想要的数据是否有区别:

data = {position: [{X:12},{Y:4}] ,name : 'Smth'}

以下方法有什么不同吗:

const X = data.position[0].X
for(...){
...do somthing with X
}

for(...){
...do somthing with data.position[0].X
}

最佳答案

是的,有些不同是存在的。每次调用属性 js 解释器 try to find calling property (或方法)在原型(prototype)层次结构中。

Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.

如果你使用变量来缓存一些数据,它会比你使用直接访问更快。 There is some great benchmark to test it.

关于javascript - 如果我们将对象的属性分配给另一个变量然后使用它,是否会影响代码的速度效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47258706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com