Javascript performance consideration. Is dot operator faster than subscript notation?

后端 未结 2 969
挽巷
挽巷 2020-12-06 13:02

Is dot operator faster than subscript notation?

var obj = {x: \'5\'};
obj.x = \'some value\';
obj[\'x\'] = \'some value\';
相关标签:
2条回答
  • 2020-12-06 13:20

    This is maybe outdated information, but it is a statement affecting at least older Safari versions. From O'Reilly's Writing Efficient JavaScript:

    For most browsers, there is virtually no difference between using dot notation for object property access (data.count) and bracket notation (data["count"]). The one exception is Safari, where bracket notation is significantly slower than dot notation. This holds true even for Safari 4 and later using the Nitro JavaScript engine.

    Looks like http://jsperf.com/ has been taken down -- it says Website Disabled, but using an embedded WebKit engine from Qt4 it looks like that this statement is true, using this test:

    var t = new Date().getTime();
    var x = { c: 123 };
    
    for (var i = 0; i < 5000000; i++)
        x['c'] += 2;
    
    document.write(( new Date().getTime() - t ) + '; value ' + x.c);

    var t = new Date().getTime();
    var x = { c: 123 };
    
    for (var i = 0; i < 5000000; i++)
        x.c += 2;
    
    document.write(( new Date().getTime() - t ) + '; value ' + x.c);

    Using x['c'] took about 4 seconds while x.c ran for about 3 seconds. Current Firefox and Chrome appear to make no distinction between the two.

    0 讨论(0)
  • 2020-12-06 13:23

    Not anything incredibly worrying. Acessing variables by window or eval are significantly slower though.

    http://jsperf.com/dot-vs-square-bracket/5

    0 讨论(0)
提交回复
热议问题