有什么可以保证在JavaScript中访问对象的属性的时间? [英] Is there anything that guarantees constant time for accessing a property of an object in JavaScript?

查看:92
本文介绍了有什么可以保证在JavaScript中访问对象的属性的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于我在亚马逊采访时与访问员的辩论。



让我们创建一个对象:

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

JavaScript 保证中有什么,当我随后访问2个属性,如 Obj ['SomeProperty'] Obj [69] 各自的值函数(){console.log(Accessed some property);在O(1)时间内查找 69 我知道访问运算符 [] 给一个经验丰富的程序员的印象是他正在处理一个O(1)查找结构,但是JavaScript引擎不可能实现 Object ,使得属性在O(1)中查找?

解决方案


JavaScript中有什么保证在O(1)中查找值时间?


否。 JavaScript不提供任何复杂的保证,除了ES6系列之外,


我知道访问运算符 [] 给一个经验丰富的程序员的印象是他正在处理一个O(1)查找结构


是的,这是一个合理的期望。引擎采用各种优化,从隐藏的类遍历hashmaps到动态数组,以满足这些假设。



当然,永远不要忘记JS对象是复杂的野兽,并且访问一个简单的属性可能会触发一个getter陷阱,反过来可以做任何事情。


JavaScript引擎不可能实现Object在某种情况下,在O(1)中不查找属性?


是的,这是可能的。 $ b

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

解决方案

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.

这篇关于有什么可以保证在JavaScript中访问对象的属性的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆