开发者

javascript object property lookup

开发者 https://www.devze.com 2023-03-04 12:02 出处:网络
Due to object in javascript is associative map (HashMap in other programming languages) does next code

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) {
       开发者_JAVA百科 // I need that property name for my need
        return obj.prop();
    }

will it be twice property lookup time like

obj.prop()

or more?

Thanks.


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 (i.e. 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.


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...
0

精彩评论

暂无评论...
验证码 换一张
取 消