比较两个object.attribute或两个object更快吗?

时间:2018-09-09 06:30:06

标签: javascript

我的对象日期如下

let date = {
   string: '2018-10-09'
}

I also have two hour object :

let hour1 = {
   string: '09:00',
   date: date
}

let hour2 = {
   string: '10:00',
   date: date
}

我想检查是否hour1.date等于hour2.date或hour1.date.string等于hour2.date.string。两者之间最快的是什么,为什么?:

if (hour1.date === hour2.date) //do things
if (hour1.date.string === hour2.date.string) //do things

编辑-部分答案

好的,所以我做了如下测试:

let date = {
   string: '2018-10-09'
}

let hour1 = {
   string: '09:00',
   date: date
}

let hour2 = {
   string: '10:00',
   date: date
}

var iterations = 100000000


console.time('Object comparison');
for (var i = 0; i < iterations; i++ ){
    compareObjects(hour1.date, hour2.date);
};
console.timeEnd('Object comparison');


console.time('Property comparison');
for (var i = 0; i < iterations; i++) {
    compareObjectsProperties(hour1.date.string, hour2.date.string);
}
console.timeEnd('Property comparison');


function compareObjects(o1, o2) {
    if (o1 === o2) return true;
}

function compareObjectsProperties(prop1, prop2) {
    if (prop1 === prop2) return true;
}

输出:

Object comparison: 284.808837890625ms
Property comparison: 281.16796875ms

1 个答案:

答案 0 :(得分:2)

替代方案根本不相等:

var a = {
   str: 'aaa'
}, b = {
   str: 'aaa'
};

// true, strings are not equal
a.str === b.str; 
/*
  false, both objects are independent and so are different; 
  nested properties does not matter
*/
a === b;