简体   繁体   中英

How does JavaScript find values when using dot notation or key

I have a large JavaScript object that contains properties that are added and deleted as and when required. Something similar to this:

var data = {

  data1: {
      subscribers : ["sub1", "sub2"]
  },

  data2: {
      subscribers : ["sub1", "sub2"]
  }

  //[0...*]

};

I want the subscribers from "data2" so I use data["data2"].subscribers to access this information.

But my questions are:

  • What are JavaScript internal workings of accessing properties like this (dot notation, using the property name)?
  • Does the size of the object have an effect on how fast the subscribers array is returned?

My guess would be that the size would effect the speed of receiving the returned data because I think the way that JavaScript accesses the properties is using a for loop over the objects:

function getSubs(name) {
    for(var prop in data) {
        if(prop === name) {
            return data[prop].subscribers;
        }
    }
}
var subs = getSubs("data2");

No, it doesn't work by iterating over all the properties but basically by using the frequently used hash table pattern before compilation and classes after compilation (read more here regarding V8 ).

In fact, that's part of the internal working of javascript engines, not the specification. What you need to know is :

Yes, having many properties may have an impact but much lighter than what you seem to think. Don't worry about it.

javascript对象基本上是一个映射,因此我认为它们将在内部使用哈希表。

What are JavaScript internal workings of accessing properties like this (dot notation, using the property name)?

The premise of your question is false , JavaScript has no "internal workings"!

JavaScript is a language and describes what happens, it doesn't say how it works internally, because JavaScript has no internals.

Every implementation of JavaScript has their own way of doing things. As they fulfil the semantics (ie the what ) as described by specification, you shouldn't worry.

Because of this, the answer is: It's irrelevant .

Only if you run in a performance problem, and only when you're sure that the problem goes away when you use less properties, could you be tempted to think about the implementation. But even then, the knowledge that the problem has gone away is all you would need.

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