简体   繁体   中英

javascript object property lookup

Due to object in javascript is associative map (HashMap in other programming languages) does next code

for (var prop in object) {
    if (prop === someConcreteProperty) {
        // some decision
        break;
    }
}

slower anyhow then dummy property lookup like

if (typeof object.someConcreteProperty != 'undefined') {
    // some decision
}

Edits:

I'm thinking about performance in code like:

for ( var prop in obj)
    if (obj[prop] === someAnonymousMethod) {
        // I need that property name for my need
        return obj.prop();
    }

will it be twice property lookup time like

obj.prop()

or more?

Thanks.

I guess for the first one you meant:

if ('prop' in obj) {
  // ...
}

Then you can talk about speed differences and different behavior.

Homework:

var obj = { prop: undefined }; // a bit philosophical...

This can be tested empirically:

<script language="javascript">

alert("Initialising test object...");
var obj = new Object();
for (var i=0; i<1000000; i++) obj["prop"+i] = i;


alert("Initialised. Doing Test.");

var d1 = (new Date()).getTime();

needle = obj["prop"+(i-1)]; // last object
for (var prop in obj) {
    if (obj === needle) {
        // some decision
        break;
    }
}

var ms1 = ((new Date()).getTime()) - d1;

alert("Method 1 took "+ms1+"ms.")

var d2 = (new Date()).getTime();

if (typeof obj["prop"+(i-1)] != 'undefined') {
    // some decision
}

var ms2 = (new Date()).getTime() - d2;
alert("Method 2 took "+ms2+"ms.")

</script>

Method 1 takes MUCH longer than Method 2. This is hardly surprising since all of the computing necessary to execute Method 2 is included in Method 1 plus MUCH more.

The answer to this question becomes obvious when you understand how property lookup works in JavaScript. In the worst case, properties in JavaScript Objects are implemented as elements in a hash table.

Property lookup is, in this case, performed in constant time on average. It's good to note, though, that in very rare worst-case scenarios, hash table search time can be linear.

If you loop through a list of properties, you reduce the performance to linear time, roughly proportional to the number of properties in the object.

So, yes method 1 is always faster, and much much faster if the object has lots of properties.

Just as a side note: many modern JavaScript engines (ie Google's V8) may optimize your code for you to provide better performance. In fact, I believe Objects in V8 are implemented as real classes. In this case memory lookup is guaranteed to be constant time, unlike traditional hash table lookup.

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