简体   繁体   中英

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.

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. However the tests I have made (code athttps://gist.github.com/Edorka/fbfb0778c859d8f518f0508414d3e6a2 ) shows no difference:

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.

Nested property access is one of the most frequently executed operation in 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.

Live demo on jsperf.com

没有不同

Conclusion: don't worry about it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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