Any performance benefit to “locking down” JavaScript objects?

后端 未结 6 1993
Happy的楠姐
Happy的楠姐 2021-02-02 05:18

JavaScript 1.8.5 (ECMAScript 5) adds some interesting methods that prevent future modifications of a passed object, with varying degrees of thoroughness:

<
6条回答
  •  滥情空心
    2021-02-02 05:42

    Update: Since this answer was originally written, the bug in V8 that caused this issue has been fixed. See the answer by Jan Molak for more info.


    In Google Chrome (so V8, that is), a frozen object iterates 98% slower than a regular object.

    http://jsperf.com/performance-frozen-object

    Test name*              ops/sec
    
    non-frozen object    32,193,471
    frozen object           592,726
    

    Probably this is because those functions are relatively new and probably not optimized yet (but that's just my guess, I honestly don't know the reason).

    Anyhow, I really do not recommed using it for performance benefits, as that apparently does not make sense.


    * The code for the test is:

    var o1 = {a: 1};
    var o2 = {a: 1};
    
    Object.freeze(o2);
    

    Test 1 (non-frozen object):

    for(var key in o1);
    

    Test 2 (frozen object):

    for(var key in o2);
    

提交回复
热议问题