Javad Sameri
Javad Sameri

Reputation: 1319

Does it make diffrence in speed efficiency of code if we assign property of object to another variable and then use it?

I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :

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

is there any diffrent between the following method :

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

or

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

Upvotes: 1

Views: 58

Answers (1)

RQman
RQman

Reputation: 469

Yes, some different is exist. Every time when you call property js interpreter try to find calling property (or method) at prototype hierarchy.

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.

If you use variable to cache some data it will be faster than you use direct access. There is some great benchmark to test it.

Upvotes: 2

Related Questions