是否有任何保证在JavaScript中访问对象属性的恒定时间?
作者:互联网
这是关于我在亚马逊采访时与面试官进行的辩论.
我来创建一个对象:
var Obj = {};
Obj['SomeProperty'] = function ( ) { console.log("Accessed some property"); };
Obj[69] = true;
JavaScript中有什么保证当我随后访问Obj [‘SomeProperty’]和Obj [69]这两个属性时各自的值function(){console.log(“Accessed some property”); };在O(1)时间内查找69个?我知道访问操作符[]给一个经验丰富的程序员一个他正在处理O(1)查找结构的印象,但是JavaScript引擎不可能以一种不会查找属性的方式实现Object O(1)?
解决方法:
Is there anything in the JavaScript guaranteeing that the values are looked up in O(1) time?
不,JavaScript不提供任何复杂性保证,except for ES6 collections.
I know the access operator
[]
gives a seasoned programmer the impression that he’s dealing with an O(1) lookup structure
是的,这是一个合理的期望.引擎采用各种优化,从隐藏类到哈希映射到动态数组,以满足这些假设.
当然,永远不要忘记JS对象是复杂的野兽,访问一个简单的属性可能会触发一个getter陷阱,而这个陷阱又可以做任何事情.
Can’t it be possible for a JavaScript engine to implement Object in a way such that properties are not looked up in O(1)?
是的,这是可能的.
标签:javascript,complexity-theory,time-complexity,data-structures 来源: https://codeday.me/bug/20190609/1202115.html