javascript object property lookup

后端 未结 3 865
孤街浪徒
孤街浪徒 2021-01-16 05:10

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

for (var prop in object) {
    if (prop === someConc         


        
相关标签:
3条回答
  • 2021-01-16 05:28

    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.

    0 讨论(0)
  • 2021-01-16 05:28

    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.

    0 讨论(0)
  • 2021-01-16 05:29

    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 讨论(0)
提交回复
热议问题