Is there anything that guarantees constant time for accessing a property of an object in JavaScript?

风流意气都作罢 提交于 2019-11-26 07:49:52

问题


This is in regards to a debate I had with an interviewer when I was interviewing at Amazon.

Let\'s I create an object:

var Obj = {};
Obj[\'SomeProperty\'] = function ( ) { console.log(\"Accessed some property\"); };
Obj[69] = true;

Is there anything in the JavaScript guaranteeing that when I subsequently access those 2 properties like Obj[\'SomeProperty\'] and Obj[69] the respective values function ( ) { console.log(\"Accessed some property\"); }; and 69 are looked up in O(1) time? I know the access operator [] gives a seasoned programmer the impression that he\'s dealing with an O(1) lookup structure, but 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)?


回答1:


Is there anything in the JavaScript guaranteeing that the values are looked up in O(1) time?

No. JavaScript does not give any complexity guarantees whatsoever, 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

Yes you are, this is a reasonable expectation. Engines employ all kinds of optimisations, from hidden classes over hashmaps to dynamic arrays, to meet these assumptions.

Of course, never forget that JS objects are complex beasts, and accessing a simple property might trigger a getter trap that in turn could do anything.

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)?

Yes, that's possible.



来源:https://stackoverflow.com/questions/34292087/is-there-anything-that-guarantees-constant-time-for-accessing-a-property-of-an-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!