a.b.c.d 和 a['b']['c']['d'],哪个性能更高
应该是 a.b.c.d
比 a['b']['c']['d']
性能高点,后者还要考虑 [ ]
中是变量的情况,再者,从两种形式的结构来看,显然编译器解析前者要比后者容易些,自然也就快一点。
测试如下:
function compare(times) {
let a = { key: {} };
let temp = a;
for (let i = 0; i < times; i++) {
let tmp = temp['key'];
tmp['key'] = {};
temp = tmp;
}
temp['key']['key'] = 'surprise';
let d0 = new Date();
let i = a;
while (i['key'] !== 'surprise') {
i = i['key'];
}
console.log('[] time', new Date() - d0);
let d1 = new Date();
let ii = a;
while (ii.key !== 'surprise') {
ii = ii.key;
}
console.log('. time', new Date() - d1);
}
然而:O(n)或者O(2n)时间复杂度都是n,在统计上都是一个量级,比较没有太大意义