简体   繁体   English

javascript 中的属性与常量访问

[英]Attribute vs constant access in javascript

I'm working on High-performance oriented web components and I doubt if it's worths assign an object attribute's value to a constant before accessing it multiple times.我正在研究面向高性能的 web 组件,我怀疑是否值得在多次访问之前将 object 属性的值分配给常量。

I mean turning this:我的意思是转这个:

let counter = 0;
for (let i = 0, len = parentObject.myObject.items.length; i < len; i++) {
    // items is an array of integers
    counter += parentObject.myObject.items[i] ;
}

Into this:进入这个:

let counter = 0;
const { myObject } = parentObject;
const { items } = myObject;
for (let i = 0, len =items.length; i < len; i++) { 
    counter += items[i] ;
}

In Python this change would have a sentitive impact in performance.在 Python 中,此更改将对性能产生敏感影响。 However the tests I have made (code athttps://gist.github.com/Edorka/fbfb0778c859d8f518f0508414d3e6a2 ) shows no difference:但是我所做的测试(代码在https://gist.github.com/Edorka/fbfb0778c859d8f518f0508414d3e6a2 )显示没有区别:

caseA total 124999750000
Execution time (hr): 0s 1.88101ms
caseB total 124999750000
Execution time (hr): 0s 1.117547ms

I doubt if I'm making my tests wrong or if the VM has any optimization for this case I'm not aware of.我怀疑我的测试是否错误,或者虚拟机是否针对这种我不知道的情况进行了优化。

UPDATE: Following @George Jempty suggestion I made a quick adaptation on JSPerf at https://jsperf.com/attribute-vs-constants but results keep being quite erratic.更新:根据@George Jempty 的建议,我在https://jsperf.com/attribute-vs-constants对 JSPerf 进行了快速调整,但结果一直很不稳定。

Nested property access is one of the most frequently executed operation in JavaScript.嵌套属性访问是 JavaScript 中最常执行的操作之一。 You can expect it to be heavily optimized.您可以期望它会进行大量优化。

Indeed, the V8 engine caches object properties at run time, so the performance benefit of caching manually would be negligible.事实上,V8 引擎在运行时缓存object 属性,因此手动缓存的性能优势可以忽略不计。

Live demo on jsperf.com jsperf.com 上的现场演示

没有不同

Conclusion: don't worry about it!结论:不用担心!

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

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